Coverage Report

Created: 2023-04-06 10:12

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.89.5 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - Read FAQ at http://dearimgui.org/faq
6
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
7
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
8
// Read imgui.cpp for details, links and comments.
9
10
// Resources:
11
// - FAQ                   http://dearimgui.org/faq
12
// - Homepage & latest     https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/5886 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
19
// Getting Started?
20
// - For first-time users having issues compiling/linking/running or issues loading fonts:
21
//   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
23
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
24
// See LICENSE.txt for copyright and licensing details (standard MIT License).
25
// This library is free but needs your support to sustain development and maintenance.
26
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
27
// Individuals: you can support continued development via donations. See docs/README or web page.
28
29
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
30
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
31
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
32
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
33
// to a better solution or official support for them.
34
35
/*
36
37
Index of this file:
38
39
DOCUMENTATION
40
41
- MISSION STATEMENT
42
- CONTROLS GUIDE
43
- PROGRAMMER GUIDE
44
  - READ FIRST
45
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
46
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
47
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
48
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
49
- API BREAKING CHANGES (read me when you update!)
50
- FREQUENTLY ASKED QUESTIONS (FAQ)
51
  - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
52
53
CODE
54
(search for "[SECTION]" in the code to find them)
55
56
// [SECTION] INCLUDES
57
// [SECTION] FORWARD DECLARATIONS
58
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
59
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
60
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
61
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
62
// [SECTION] MISC HELPERS/UTILITIES (File functions)
63
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
64
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
65
// [SECTION] ImGuiStorage
66
// [SECTION] ImGuiTextFilter
67
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
68
// [SECTION] ImGuiListClipper
69
// [SECTION] STYLING
70
// [SECTION] RENDER HELPERS
71
// [SECTION] INITIALIZATION, SHUTDOWN
72
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
73
// [SECTION] INPUTS
74
// [SECTION] ERROR CHECKING
75
// [SECTION] LAYOUT
76
// [SECTION] SCROLLING
77
// [SECTION] TOOLTIPS
78
// [SECTION] POPUPS
79
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
80
// [SECTION] DRAG AND DROP
81
// [SECTION] LOGGING/CAPTURING
82
// [SECTION] SETTINGS
83
// [SECTION] LOCALIZATION
84
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
85
// [SECTION] DOCKING
86
// [SECTION] PLATFORM DEPENDENT HELPERS
87
// [SECTION] METRICS/DEBUGGER WINDOW
88
// [SECTION] DEBUG LOG WINDOW
89
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
90
91
*/
92
93
//-----------------------------------------------------------------------------
94
// DOCUMENTATION
95
//-----------------------------------------------------------------------------
96
97
/*
98
99
 MISSION STATEMENT
100
 =================
101
102
 - Easy to use to create code-driven and data-driven tools.
103
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
104
 - Easy to hack and improve.
105
 - Minimize setup and maintenance.
106
 - Minimize state storage on user side.
107
 - Minimize state synchronization.
108
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
109
 - Efficient runtime and memory consumption.
110
111
 Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
112
113
 - Doesn't look fancy, doesn't animate.
114
 - Limited layout features, intricate layouts are typically crafted in code.
115
116
117
 CONTROLS GUIDE
118
 ==============
119
120
 - MOUSE CONTROLS
121
   - Mouse wheel:                   Scroll vertically.
122
   - SHIFT+Mouse wheel:             Scroll horizontally.
123
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
124
   - Click ^, Double-Click title:   Collapse window.
125
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
126
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
127
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
128
129
 - TEXT EDITOR
130
   - Hold SHIFT or Drag Mouse:      Select text.
131
   - CTRL+Left/Right:               Word jump.
132
   - CTRL+Shift+Left/Right:         Select words.
133
   - CTRL+A or Double-Click:        Select All.
134
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
135
   - CTRL+Z, CTRL+Y:                Undo, Redo.
136
   - ESCAPE:                        Revert text to its original value.
137
   - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
138
139
 - KEYBOARD CONTROLS
140
   - Basic:
141
     - Tab, SHIFT+Tab               Cycle through text editable fields.
142
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
143
     - CTRL+Click                   Input text into a Slider or Drag widget.
144
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
145
     - Tab, SHIFT+Tab:              Cycle through every items.
146
     - Arrow keys                   Move through items using directional navigation. Tweak value.
147
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
148
     - Enter                        Activate item (prefer text input when possible).
149
     - Space                        Activate item (prefer tweaking with arrows when possible).
150
     - Escape                       Deactivate item, leave child window, close popup.
151
     - Page Up, Page Down           Previous page, next page.
152
     - Home, End                    Scroll to top, scroll to bottom.
153
     - Alt                          Toggle between scrolling layer and menu layer.
154
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
155
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
156
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
157
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
158
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
159
160
 - GAMEPAD CONTROLS
161
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
162
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
163
   - Download controller mapping PNG/PSD at http://dearimgui.org/controls_sheets
164
   - Backend support: backend needs to:
165
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
166
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
167
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
168
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
169
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
170
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
171
172
 - REMOTE INPUTS SHARING & MOUSE EMULATION
173
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
174
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
175
     in order to share your PC mouse/keyboard.
176
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
177
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
178
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
179
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
180
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
181
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
182
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
183
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
184
185
186
 PROGRAMMER GUIDE
187
 ================
188
189
 READ FIRST
190
 ----------
191
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
192
 - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
193
   destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
194
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
195
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
196
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
197
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
198
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
199
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
200
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
201
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
202
 - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
203
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
204
   If you get an assert, read the messages and comments around the assert.
205
 - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
206
 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
207
   See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
208
   However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
209
 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
210
211
212
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
213
 ----------------------------------------------
214
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
215
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
216
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
217
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
218
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
219
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
220
   likely be a comment about it. Please report any issue to the GitHub page!
221
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
222
 - Try to keep your copy of Dear ImGui reasonably up to date.
223
224
225
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
226
 ---------------------------------------------------------------
227
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
228
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
229
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
230
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
231
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
232
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
233
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
234
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
235
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
236
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
237
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
238
239
240
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
241
 --------------------------------------
242
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
243
 The sub-folders in examples/ contain examples applications following this structure.
244
245
     // Application init: create a dear imgui context, setup some options, load fonts
246
     ImGui::CreateContext();
247
     ImGuiIO& io = ImGui::GetIO();
248
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
249
     // TODO: Fill optional fields of the io structure later.
250
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
251
252
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
253
     ImGui_ImplWin32_Init(hwnd);
254
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
255
256
     // Application main loop
257
     while (true)
258
     {
259
         // Feed inputs to dear imgui, start new frame
260
         ImGui_ImplDX11_NewFrame();
261
         ImGui_ImplWin32_NewFrame();
262
         ImGui::NewFrame();
263
264
         // Any application code here
265
         ImGui::Text("Hello, world!");
266
267
         // Render dear imgui into screen
268
         ImGui::Render();
269
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
270
         g_pSwapChain->Present(1, 0);
271
     }
272
273
     // Shutdown
274
     ImGui_ImplDX11_Shutdown();
275
     ImGui_ImplWin32_Shutdown();
276
     ImGui::DestroyContext();
277
278
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
279
280
     // Application init: create a dear imgui context, setup some options, load fonts
281
     ImGui::CreateContext();
282
     ImGuiIO& io = ImGui::GetIO();
283
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
284
     // TODO: Fill optional fields of the io structure later.
285
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
286
287
     // Build and load the texture atlas into a texture
288
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
289
     int width, height;
290
     unsigned char* pixels = NULL;
291
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
292
293
     // At this point you've got the texture data and you need to upload that to your graphic system:
294
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
295
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
296
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
297
     io.Fonts->SetTexID((void*)texture);
298
299
     // Application main loop
300
     while (true)
301
     {
302
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
303
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
304
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
305
        io.DisplaySize.x = 1920.0f;             // set the current display width
306
        io.DisplaySize.y = 1280.0f;             // set the current display height here
307
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
308
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
309
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
310
311
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
312
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
313
        ImGui::NewFrame();
314
315
        // Most of your application code here
316
        ImGui::Text("Hello, world!");
317
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
318
        MyGameRender(); // may use any Dear ImGui functions as well!
319
320
        // Render dear imgui, swap buffers
321
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
322
        ImGui::EndFrame();
323
        ImGui::Render();
324
        ImDrawData* draw_data = ImGui::GetDrawData();
325
        MyImGuiRenderFunction(draw_data);
326
        SwapBuffers();
327
     }
328
329
     // Shutdown
330
     ImGui::DestroyContext();
331
332
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
333
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
334
 Please read the FAQ and example applications for details about this!
335
336
337
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
338
 ---------------------------------------------
339
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
340
341
    void MyImGuiRenderFunction(ImDrawData* draw_data)
342
    {
343
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
344
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
345
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
346
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
347
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
348
       ImVec2 clip_off = draw_data->DisplayPos;
349
       for (int n = 0; n < draw_data->CmdListsCount; n++)
350
       {
351
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
352
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
353
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
354
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
355
          {
356
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
357
             if (pcmd->UserCallback)
358
             {
359
                 pcmd->UserCallback(cmd_list, pcmd);
360
             }
361
             else
362
             {
363
                 // Project scissor/clipping rectangles into framebuffer space
364
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
365
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
366
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
367
                     continue;
368
369
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
370
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
371
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
372
                 // - Clipping coordinates are provided in imgui coordinates space:
373
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
374
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
375
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
376
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
377
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
378
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
379
380
                 // The texture for the draw call is specified by pcmd->GetTexID().
381
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
382
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
383
384
                 // Render 'pcmd->ElemCount/3' indexed triangles.
385
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
386
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
387
             }
388
          }
389
       }
390
    }
391
392
393
 API BREAKING CHANGES
394
 ====================
395
396
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
397
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
398
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
399
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
400
401
(Docking/Viewport Branch)
402
 - 2023/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
403
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
404
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
405
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
406
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
407
408
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
409
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
410
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
411
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
412
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
413
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
414
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
415
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
416
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
417
                         it has been frequently requested by people to use our own. We had an opt-in define which was
418
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
419
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
420
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
421
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
422
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
423
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
424
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
425
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
426
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
427
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
428
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
429
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
430
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
431
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
432
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
433
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
434
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
435
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
436
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
437
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
438
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
439
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
440
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
441
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
442
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
443
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
444
                         - previously this would make the window content size ~200x200:
445
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
446
                         - instead, please submit an item:
447
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
448
                         - alternative:
449
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
450
                         - content size is now only extended when submitting an item!
451
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
452
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
453
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
454
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
455
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
456
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
457
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
458
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
459
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
460
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
461
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
462
                        - Official backends from 1.87+                  -> no issue.
463
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
464
                        - Custom backends not writing to io.NavInputs[] -> no issue.
465
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
466
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
467
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
468
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
469
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
470
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
471
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
472
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
473
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
474
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
475
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
476
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
477
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
478
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
479
                       read https://github.com/ocornut/imgui/issues/4921 for details.
480
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
481
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
482
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
483
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
484
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
485
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
486
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
487
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
488
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
489
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
490
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
491
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
492
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
493
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
494
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
495
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
496
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
497
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
498
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
499
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
500
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
501
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
502
                        - if you are using official backends from the source tree: you have nothing to do.
503
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
504
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
505
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
506
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
507
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
508
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
509
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
510
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
511
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
512
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
513
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
514
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
515
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
516
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
517
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
518
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
519
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
520
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
521
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
522
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
523
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
524
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
525
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
526
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
527
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
528
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
529
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
530
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
531
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
532
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
533
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
534
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
535
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
536
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
537
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
538
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
539
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
540
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
541
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
542
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
543
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
544
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
545
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
546
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
547
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
548
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
549
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
550
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
551
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
552
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
553
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
554
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
555
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
556
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
557
                       - if you omitted the 'power' parameter (likely!), you are not affected.
558
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
559
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
560
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
561
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
562
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
563
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
564
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
565
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
566
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
567
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
568
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
569
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
570
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
571
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
572
                       - ShowTestWindow()                    -> use ShowDemoWindow()
573
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
574
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
575
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
576
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
577
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
578
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
579
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
580
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
581
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
582
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
583
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
584
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
585
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
586
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
587
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
588
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
589
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
590
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
591
                       - ImFont::Glyph                       -> use ImFontGlyph
592
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
593
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
594
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
595
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
596
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
597
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
598
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
599
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
600
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
601
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
602
                       Please reach out if you are affected.
603
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
604
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
605
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
606
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
607
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
608
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
609
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
610
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
611
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
612
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
613
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
614
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
615
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
616
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
617
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
618
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
619
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
620
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
621
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
622
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
623
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
624
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
625
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
626
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
627
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
628
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
629
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
630
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
631
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
632
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
633
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
634
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
635
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
636
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
637
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
638
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
639
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
640
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
641
                       consistent with other functions. Kept redirection functions (will obsolete).
642
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
643
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
644
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
645
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
646
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
647
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
648
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
649
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
650
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
651
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
652
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
653
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
654
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
655
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
656
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
657
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
658
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
659
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
660
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
661
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
662
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
663
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
664
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
665
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
666
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
667
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
668
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
669
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
670
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
671
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
672
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
673
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
674
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
675
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
676
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
677
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
678
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
679
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
680
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
681
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
682
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
683
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
684
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
685
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
686
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
687
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
688
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
689
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
690
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
691
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
692
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
693
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
694
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
695
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
696
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
697
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
698
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
699
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
700
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
701
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
702
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
703
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
704
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
705
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
706
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
707
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
708
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
709
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
710
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
711
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
712
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
713
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
714
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
715
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
716
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
717
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
718
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
719
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
720
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
721
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
722
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
723
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
724
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
725
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
726
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
727
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
728
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
729
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
730
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
731
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
732
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
733
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
734
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
735
                     - the signature of the io.RenderDrawListsFn handler has changed!
736
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
737
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
738
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
739
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
740
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
741
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
742
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
743
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
744
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
745
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
746
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
747
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
748
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
749
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
750
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
751
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
752
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
753
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
754
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
755
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
756
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
757
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
758
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
759
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
760
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
761
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
762
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
763
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
764
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
765
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
766
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
767
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
768
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
769
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
770
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
771
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
772
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
773
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
774
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
775
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
776
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
777
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
778
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
779
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
780
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
781
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
782
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
783
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
784
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
785
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
786
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
787
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
788
789
790
 FREQUENTLY ASKED QUESTIONS (FAQ)
791
 ================================
792
793
 Read all answers online:
794
   https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
795
 Read all answers locally (with a text editor or ideally a Markdown viewer):
796
   docs/FAQ.md
797
 Some answers are copied down here to facilitate searching in code.
798
799
 Q&A: Basics
800
 ===========
801
802
 Q: Where is the documentation?
803
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
804
    - Run the examples/ and explore them.
805
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
806
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
807
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
808
    - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
809
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
810
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
811
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
812
    - Your programming IDE is your friend, find the type or function declaration to find comments
813
      associated with it.
814
815
 Q: What is this library called?
816
 Q: Which version should I get?
817
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
818
 >> See https://www.dearimgui.org/faq for details.
819
820
 Q&A: Integration
821
 ================
822
823
 Q: How to get started?
824
 A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
825
826
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
827
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
828
 >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.
829
830
 Q. How can I enable keyboard controls?
831
 Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
832
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
833
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
834
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
835
 >> See https://www.dearimgui.org/faq
836
837
 Q&A: Usage
838
 ----------
839
840
 Q: About the ID Stack system..
841
   - Why is my widget not reacting when I click on it?
842
   - How can I have widgets with an empty label?
843
   - How can I have multiple widgets with the same label?
844
   - How can I have multiple windows with the same label?
845
 Q: How can I display an image? What is ImTextureID, how does it work?
846
 Q: How can I use my own math types instead of ImVec2/ImVec4?
847
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
848
 Q: How can I display custom shapes? (using low-level ImDrawList API)
849
 >> See https://www.dearimgui.org/faq
850
851
 Q&A: Fonts, Text
852
 ================
853
854
 Q: How should I handle DPI in my application?
855
 Q: How can I load a different font than the default?
856
 Q: How can I easily use icons in my application?
857
 Q: How can I load multiple fonts?
858
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
859
 >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
860
861
 Q&A: Concerns
862
 =============
863
864
 Q: Who uses Dear ImGui?
865
 Q: Can you create elaborate/serious tools with Dear ImGui?
866
 Q: Can you reskin the look of Dear ImGui?
867
 Q: Why using C++ (as opposed to C)?
868
 >> See https://www.dearimgui.org/faq
869
870
 Q&A: Community
871
 ==============
872
873
 Q: How can I help?
874
 A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
875
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
876
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
877
    - Individuals: you can support continued development via PayPal donations. See README.
878
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
879
      and see how you want to help and can help!
880
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
881
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
882
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
883
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
884
885
*/
886
887
//-------------------------------------------------------------------------
888
// [SECTION] INCLUDES
889
//-------------------------------------------------------------------------
890
891
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
892
#define _CRT_SECURE_NO_WARNINGS
893
#endif
894
895
#ifndef IMGUI_DEFINE_MATH_OPERATORS
896
#define IMGUI_DEFINE_MATH_OPERATORS
897
#endif
898
899
#include "imgui.h"
900
#ifndef IMGUI_DISABLE
901
#include "imgui_internal.h"
902
903
// System includes
904
#include <stdio.h>      // vsnprintf, sscanf, printf
905
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
906
#include <stddef.h>     // intptr_t
907
#else
908
#include <stdint.h>     // intptr_t
909
#endif
910
911
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
912
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
913
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
914
#endif
915
916
// [Windows] OS specific includes (optional)
917
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
918
#define IMGUI_DISABLE_WIN32_FUNCTIONS
919
#endif
920
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
921
#ifndef WIN32_LEAN_AND_MEAN
922
#define WIN32_LEAN_AND_MEAN
923
#endif
924
#ifndef NOMINMAX
925
#define NOMINMAX
926
#endif
927
#ifndef __MINGW32__
928
#include <Windows.h>        // _wfopen, OpenClipboard
929
#else
930
#include <windows.h>
931
#endif
932
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
933
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
934
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
935
#endif
936
#endif
937
938
// [Apple] OS specific includes
939
#if defined(__APPLE__)
940
#include <TargetConditionals.h>
941
#endif
942
943
// Visual Studio warnings
944
#ifdef _MSC_VER
945
#pragma warning (disable: 4127)             // condition expression is constant
946
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
947
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
948
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
949
#endif
950
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
951
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
952
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
953
#endif
954
955
// Clang/GCC warnings with -Weverything
956
#if defined(__clang__)
957
#if __has_warning("-Wunknown-warning-option")
958
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
959
#endif
960
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
961
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
962
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
963
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
964
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
965
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
966
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
967
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
968
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
969
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
970
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
971
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
972
#elif defined(__GNUC__)
973
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
974
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
975
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
976
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
977
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
978
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
979
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
980
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
981
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
982
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
983
#endif
984
985
// Debug options
986
47.5k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
987
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
988
#define IMGUI_DEBUG_INI_SETTINGS    0   // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
989
990
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
991
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
992
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
993
994
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
995
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
996
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
997
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
998
999
// Docking
1000
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1001
static const float DOCKING_SPLITTER_SIZE                    = 2.0f;
1002
1003
//-------------------------------------------------------------------------
1004
// [SECTION] FORWARD DECLARATIONS
1005
//-------------------------------------------------------------------------
1006
1007
static void             SetCurrentWindow(ImGuiWindow* window);
1008
static void             FindHoveredWindow();
1009
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1010
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1011
1012
static void             AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
1013
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1014
1015
// Settings
1016
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1017
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1018
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1019
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1020
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1021
1022
// Platform Dependents default implementation for IO functions
1023
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1024
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1025
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1026
1027
namespace ImGui
1028
{
1029
// Navigation
1030
static void             NavUpdate();
1031
static void             NavUpdateWindowing();
1032
static void             NavUpdateWindowingOverlay();
1033
static void             NavUpdateCancelRequest();
1034
static void             NavUpdateCreateMoveRequest();
1035
static void             NavUpdateCreateTabbingRequest();
1036
static float            NavUpdatePageUpPageDown();
1037
static inline void      NavUpdateAnyRequestFlag();
1038
static void             NavUpdateCreateWrappingRequest();
1039
static void             NavEndFrame();
1040
static bool             NavScoreItem(ImGuiNavItemData* result);
1041
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1042
static void             NavProcessItem();
1043
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1044
static ImVec2           NavCalcPreferredRefPos();
1045
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1046
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1047
static void             NavRestoreLayer(ImGuiNavLayer layer);
1048
static void             NavRestoreHighlightAfterMove();
1049
static int              FindWindowFocusIndex(ImGuiWindow* window);
1050
1051
// Error Checking and Debug Tools
1052
static void             ErrorCheckNewFrameSanityChecks();
1053
static void             ErrorCheckEndFrameSanityChecks();
1054
static void             UpdateDebugToolItemPicker();
1055
static void             UpdateDebugToolStackQueries();
1056
1057
// Inputs
1058
static void             UpdateKeyboardInputs();
1059
static void             UpdateMouseInputs();
1060
static void             UpdateMouseWheel();
1061
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1062
1063
// Misc
1064
static void             UpdateSettings();
1065
static bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1066
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1067
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1068
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1069
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1070
static void             RenderDimmedBackgrounds();
1071
static ImGuiWindow*     FindBlockingModal(ImGuiWindow* window);
1072
1073
// Viewports
1074
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1075
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1076
static void             DestroyViewport(ImGuiViewportP* viewport);
1077
static void             UpdateViewportsNewFrame();
1078
static void             UpdateViewportsEndFrame();
1079
static void             WindowSelectViewport(ImGuiWindow* window);
1080
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1081
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1082
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1083
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1084
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1085
static int              FindPlatformMonitorForRect(const ImRect& r);
1086
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1087
1088
}
1089
1090
//-----------------------------------------------------------------------------
1091
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1092
//-----------------------------------------------------------------------------
1093
1094
// DLL users:
1095
// - Heaps and globals are not shared across DLL boundaries!
1096
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1097
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1098
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1099
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1100
1101
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1102
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1103
//   Change to a different context by calling ImGui::SetCurrentContext().
1104
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1105
//   If you want thread-safety to allow N threads to access N different contexts:
1106
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1107
//         struct ImGuiContext;
1108
//         extern thread_local ImGuiContext* MyImGuiTLS;
1109
//         #define GImGui MyImGuiTLS
1110
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1111
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1112
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1113
// - DLL users: read comments above.
1114
#ifndef GImGui
1115
ImGuiContext*   GImGui = NULL;
1116
#endif
1117
1118
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1119
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1120
// - DLL users: read comments above.
1121
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1122
1.22k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1123
1.18k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1124
#else
1125
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1126
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1127
#endif
1128
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1129
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1130
static void*                GImAllocatorUserData = NULL;
1131
1132
//-----------------------------------------------------------------------------
1133
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1134
//-----------------------------------------------------------------------------
1135
1136
ImGuiStyle::ImGuiStyle()
1137
1
{
1138
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1139
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1140
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1141
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1142
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1143
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1144
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1145
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1146
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1147
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1148
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1149
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1150
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1151
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1152
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1153
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1154
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1155
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell
1156
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1157
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1158
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1159
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1160
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1161
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1162
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1163
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1164
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1165
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1166
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1167
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1168
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1169
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1170
1
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1171
1
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1172
1
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1173
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1174
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1175
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1176
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1177
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1178
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1179
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1180
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1181
1182
    // Default theme
1183
1
    ImGui::StyleColorsDark(this);
1184
1
}
1185
1186
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1187
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1188
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1189
0
{
1190
0
    WindowPadding = ImFloor(WindowPadding * scale_factor);
1191
0
    WindowRounding = ImFloor(WindowRounding * scale_factor);
1192
0
    WindowMinSize = ImFloor(WindowMinSize * scale_factor);
1193
0
    ChildRounding = ImFloor(ChildRounding * scale_factor);
1194
0
    PopupRounding = ImFloor(PopupRounding * scale_factor);
1195
0
    FramePadding = ImFloor(FramePadding * scale_factor);
1196
0
    FrameRounding = ImFloor(FrameRounding * scale_factor);
1197
0
    ItemSpacing = ImFloor(ItemSpacing * scale_factor);
1198
0
    ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
1199
0
    CellPadding = ImFloor(CellPadding * scale_factor);
1200
0
    TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
1201
0
    IndentSpacing = ImFloor(IndentSpacing * scale_factor);
1202
0
    ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
1203
0
    ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
1204
0
    ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
1205
0
    GrabMinSize = ImFloor(GrabMinSize * scale_factor);
1206
0
    GrabRounding = ImFloor(GrabRounding * scale_factor);
1207
0
    LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
1208
0
    TabRounding = ImFloor(TabRounding * scale_factor);
1209
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1210
0
    SeparatorTextPadding = ImFloor(SeparatorTextPadding * scale_factor);
1211
0
    DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
1212
0
    DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
1213
0
    MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
1214
0
}
1215
1216
ImGuiIO::ImGuiIO()
1217
1
{
1218
    // Most fields are initialized with zero
1219
1
    memset(this, 0, sizeof(*this));
1220
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1221
1222
    // Settings
1223
1
    ConfigFlags = ImGuiConfigFlags_None;
1224
1
    BackendFlags = ImGuiBackendFlags_None;
1225
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1226
1
    DeltaTime = 1.0f / 60.0f;
1227
1
    IniSavingRate = 5.0f;
1228
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1229
1
    LogFilename = "imgui_log.txt";
1230
1
    MouseDoubleClickTime = 0.30f;
1231
1
    MouseDoubleClickMaxDist = 6.0f;
1232
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1233
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1234
        KeyMap[i] = -1;
1235
#endif
1236
1
    KeyRepeatDelay = 0.275f;
1237
1
    KeyRepeatRate = 0.050f;
1238
1
    HoverDelayNormal = 0.30f;
1239
1
    HoverDelayShort = 0.10f;
1240
1
    UserData = NULL;
1241
1242
1
    Fonts = NULL;
1243
1
    FontGlobalScale = 1.0f;
1244
1
    FontDefault = NULL;
1245
1
    FontAllowUserScaling = false;
1246
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1247
1248
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1249
1
    ConfigDockingNoSplit = false;
1250
1
    ConfigDockingWithShift = false;
1251
1
    ConfigDockingAlwaysTabBar = false;
1252
1
    ConfigDockingTransparentPayload = false;
1253
1254
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1255
1
    ConfigViewportsNoAutoMerge = false;
1256
1
    ConfigViewportsNoTaskBarIcon = false;
1257
1
    ConfigViewportsNoDecoration = true;
1258
1
    ConfigViewportsNoDefaultParent = false;
1259
1260
    // Miscellaneous options
1261
1
    MouseDrawCursor = false;
1262
#ifdef __APPLE__
1263
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1264
#else
1265
1
    ConfigMacOSXBehaviors = false;
1266
1
#endif
1267
1
    ConfigInputTrickleEventQueue = true;
1268
1
    ConfigInputTextCursorBlink = true;
1269
1
    ConfigInputTextEnterKeepActive = false;
1270
1
    ConfigDragClickToInputText = false;
1271
1
    ConfigWindowsResizeFromEdges = true;
1272
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1273
1
    ConfigMemoryCompactTimer = 60.0f;
1274
1
    ConfigDebugBeginReturnValueOnce = false;
1275
1
    ConfigDebugBeginReturnValueLoop = false;
1276
1277
    // Platform Functions
1278
    // Note: Initialize() will setup default clipboard/ime handlers.
1279
1
    BackendPlatformName = BackendRendererName = NULL;
1280
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1281
1282
    // Input (NB: we already have memset zero the entire structure!)
1283
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1284
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1285
1
    MouseDragThreshold = 6.0f;
1286
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1287
141
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1288
1
    AppAcceptingEvents = true;
1289
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1290
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1291
1
}
1292
1293
// Pass in translated ASCII characters for text input.
1294
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1295
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1296
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1297
void ImGuiIO::AddInputCharacter(unsigned int c)
1298
3.79k
{
1299
3.79k
    IM_ASSERT(Ctx != NULL);
1300
3.79k
    ImGuiContext& g = *Ctx;
1301
3.79k
    if (c == 0 || !AppAcceptingEvents)
1302
261
        return;
1303
1304
3.53k
    ImGuiInputEvent e;
1305
3.53k
    e.Type = ImGuiInputEventType_Text;
1306
3.53k
    e.Source = ImGuiInputSource_Keyboard;
1307
3.53k
    e.Text.Char = c;
1308
3.53k
    g.InputEventsQueue.push_back(e);
1309
3.53k
}
1310
1311
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1312
// we should save the high surrogate.
1313
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1314
3.62k
{
1315
3.62k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1316
184
        return;
1317
1318
3.43k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1319
500
    {
1320
500
        if (InputQueueSurrogate != 0)
1321
273
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1322
500
        InputQueueSurrogate = c;
1323
500
        return;
1324
500
    }
1325
1326
2.93k
    ImWchar cp = c;
1327
2.93k
    if (InputQueueSurrogate != 0)
1328
211
    {
1329
211
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1330
201
        {
1331
201
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1332
201
        }
1333
10
        else
1334
10
        {
1335
10
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1336
10
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1337
#else
1338
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1339
#endif
1340
10
        }
1341
1342
211
        InputQueueSurrogate = 0;
1343
211
    }
1344
2.93k
    AddInputCharacter((unsigned)cp);
1345
2.93k
}
1346
1347
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1348
37
{
1349
37
    if (!AppAcceptingEvents)
1350
0
        return;
1351
37
    while (*utf8_chars != 0)
1352
0
    {
1353
0
        unsigned int c = 0;
1354
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1355
0
        AddInputCharacter(c);
1356
0
    }
1357
37
}
1358
1359
// FIXME: Perhaps we could clear queued events as well?
1360
void ImGuiIO::ClearInputCharacters()
1361
5.12k
{
1362
5.12k
    InputQueueCharacters.resize(0);
1363
5.12k
}
1364
1365
// FIXME: Perhaps we could clear queued events as well?
1366
void ImGuiIO::ClearInputKeys()
1367
5.28k
{
1368
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1369
    memset(KeysDown, 0, sizeof(KeysDown));
1370
#endif
1371
744k
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1372
739k
    {
1373
739k
        KeysData[n].Down             = false;
1374
739k
        KeysData[n].DownDuration     = -1.0f;
1375
739k
        KeysData[n].DownDurationPrev = -1.0f;
1376
739k
    }
1377
5.28k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1378
5.28k
    KeyMods = ImGuiMod_None;
1379
5.28k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1380
31.6k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1381
26.4k
    {
1382
26.4k
        MouseDown[n] = false;
1383
26.4k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1384
26.4k
    }
1385
5.28k
    MouseWheel = MouseWheelH = 0.0f;
1386
5.28k
}
1387
1388
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1389
6.07k
{
1390
6.07k
    ImGuiContext& g = *ctx;
1391
8.69k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1392
4.60k
    {
1393
4.60k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1394
4.60k
        if (e->Type != type)
1395
1.57k
            continue;
1396
3.03k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1397
295
            continue;
1398
2.74k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1399
751
            continue;
1400
1.99k
        return e;
1401
2.74k
    }
1402
4.08k
    return NULL;
1403
6.07k
}
1404
1405
// Queue a new key down/up event.
1406
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1407
// - bool down:          Is the key down? use false to signify a key release.
1408
// - float analog_value: 0.0f..1.0f
1409
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1410
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1411
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1412
1.57k
{
1413
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1414
1.57k
    IM_ASSERT(Ctx != NULL);
1415
1.57k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1416
0
        return;
1417
1.57k
    ImGuiContext& g = *Ctx;
1418
1.57k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1419
1.57k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1420
1.57k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1421
1422
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1423
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1424
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1425
    if (BackendUsingLegacyKeyArrays == -1)
1426
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1427
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1428
    BackendUsingLegacyKeyArrays = 0;
1429
#endif
1430
1.57k
    if (ImGui::IsGamepadKey(key))
1431
41
        BackendUsingLegacyNavInputArray = false;
1432
1433
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1434
1.57k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1435
1.57k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1436
1.57k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1437
1.57k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1438
1.57k
    if (latest_key_down == down && latest_key_analog == analog_value)
1439
213
        return;
1440
1441
    // Add event
1442
1.36k
    ImGuiInputEvent e;
1443
1.36k
    e.Type = ImGuiInputEventType_Key;
1444
1.36k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1445
1.36k
    e.Key.Key = key;
1446
1.36k
    e.Key.Down = down;
1447
1.36k
    e.Key.AnalogValue = analog_value;
1448
1.36k
    g.InputEventsQueue.push_back(e);
1449
1.36k
}
1450
1451
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1452
1.18k
{
1453
1.18k
    if (!AppAcceptingEvents)
1454
0
        return;
1455
1.18k
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1456
1.18k
}
1457
1458
// [Optional] Call after AddKeyEvent().
1459
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1460
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1461
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1462
0
{
1463
0
    if (key == ImGuiKey_None)
1464
0
        return;
1465
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1466
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1467
0
    IM_UNUSED(native_keycode);  // Yet unused
1468
0
    IM_UNUSED(native_scancode); // Yet unused
1469
1470
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1471
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1472
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1473
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1474
        return;
1475
    KeyMap[legacy_key] = key;
1476
    KeyMap[key] = legacy_key;
1477
#else
1478
0
    IM_UNUSED(key);
1479
0
    IM_UNUSED(native_legacy_index);
1480
0
#endif
1481
0
}
1482
1483
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1484
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1485
0
{
1486
0
    AppAcceptingEvents = accepting_events;
1487
0
}
1488
1489
// Queue a mouse move event
1490
void ImGuiIO::AddMousePosEvent(float x, float y)
1491
1.43k
{
1492
1.43k
    IM_ASSERT(Ctx != NULL);
1493
1.43k
    ImGuiContext& g = *Ctx;
1494
1.43k
    if (!AppAcceptingEvents)
1495
0
        return;
1496
1497
    // Apply same flooring as UpdateMouseInputs()
1498
1.43k
    ImVec2 pos((x > -FLT_MAX) ? ImFloorSigned(x) : x, (y > -FLT_MAX) ? ImFloorSigned(y) : y);
1499
1500
    // Filter duplicate
1501
1.43k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1502
1.43k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1503
1.43k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1504
397
        return;
1505
1506
1.03k
    ImGuiInputEvent e;
1507
1.03k
    e.Type = ImGuiInputEventType_MousePos;
1508
1.03k
    e.Source = ImGuiInputSource_Mouse;
1509
1.03k
    e.MousePos.PosX = pos.x;
1510
1.03k
    e.MousePos.PosY = pos.y;
1511
1.03k
    g.InputEventsQueue.push_back(e);
1512
1.03k
}
1513
1514
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1515
2.57k
{
1516
2.57k
    IM_ASSERT(Ctx != NULL);
1517
2.57k
    ImGuiContext& g = *Ctx;
1518
2.57k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1519
2.57k
    if (!AppAcceptingEvents)
1520
0
        return;
1521
1522
    // Filter duplicate
1523
2.57k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1524
2.57k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1525
2.57k
    if (latest_button_down == down)
1526
1.21k
        return;
1527
1528
1.36k
    ImGuiInputEvent e;
1529
1.36k
    e.Type = ImGuiInputEventType_MouseButton;
1530
1.36k
    e.Source = ImGuiInputSource_Mouse;
1531
1.36k
    e.MouseButton.Button = mouse_button;
1532
1.36k
    e.MouseButton.Down = down;
1533
1.36k
    g.InputEventsQueue.push_back(e);
1534
1.36k
}
1535
1536
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1537
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1538
489
{
1539
489
    IM_ASSERT(Ctx != NULL);
1540
489
    ImGuiContext& g = *Ctx;
1541
1542
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1543
489
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1544
20
        return;
1545
1546
469
    ImGuiInputEvent e;
1547
469
    e.Type = ImGuiInputEventType_MouseWheel;
1548
469
    e.Source = ImGuiInputSource_Mouse;
1549
469
    e.MouseWheel.WheelX = wheel_x;
1550
469
    e.MouseWheel.WheelY = wheel_y;
1551
469
    g.InputEventsQueue.push_back(e);
1552
469
}
1553
1554
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1555
0
{
1556
0
    IM_ASSERT(Ctx != NULL);
1557
0
    ImGuiContext& g = *Ctx;
1558
0
    IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1559
0
    if (!AppAcceptingEvents)
1560
0
        return;
1561
1562
    // Filter duplicate
1563
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1564
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1565
0
    if (latest_viewport_id == viewport_id)
1566
0
        return;
1567
1568
0
    ImGuiInputEvent e;
1569
0
    e.Type = ImGuiInputEventType_MouseViewport;
1570
0
    e.Source = ImGuiInputSource_Mouse;
1571
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1572
0
    g.InputEventsQueue.push_back(e);
1573
0
}
1574
1575
void ImGuiIO::AddFocusEvent(bool focused)
1576
495
{
1577
495
    IM_ASSERT(Ctx != NULL);
1578
495
    ImGuiContext& g = *Ctx;
1579
1580
    // Filter duplicate
1581
495
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1582
495
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1583
495
    if (latest_focused == focused)
1584
205
        return;
1585
1586
290
    ImGuiInputEvent e;
1587
290
    e.Type = ImGuiInputEventType_Focus;
1588
290
    e.AppFocused.Focused = focused;
1589
290
    g.InputEventsQueue.push_back(e);
1590
290
}
1591
1592
//-----------------------------------------------------------------------------
1593
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1594
//-----------------------------------------------------------------------------
1595
1596
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1597
0
{
1598
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1599
0
    ImVec2 p_last = p1;
1600
0
    ImVec2 p_closest;
1601
0
    float p_closest_dist2 = FLT_MAX;
1602
0
    float t_step = 1.0f / (float)num_segments;
1603
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1604
0
    {
1605
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1606
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1607
0
        float dist2 = ImLengthSqr(p - p_line);
1608
0
        if (dist2 < p_closest_dist2)
1609
0
        {
1610
0
            p_closest = p_line;
1611
0
            p_closest_dist2 = dist2;
1612
0
        }
1613
0
        p_last = p_current;
1614
0
    }
1615
0
    return p_closest;
1616
0
}
1617
1618
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1619
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1620
0
{
1621
0
    float dx = x4 - x1;
1622
0
    float dy = y4 - y1;
1623
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1624
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1625
0
    d2 = (d2 >= 0) ? d2 : -d2;
1626
0
    d3 = (d3 >= 0) ? d3 : -d3;
1627
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1628
0
    {
1629
0
        ImVec2 p_current(x4, y4);
1630
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1631
0
        float dist2 = ImLengthSqr(p - p_line);
1632
0
        if (dist2 < p_closest_dist2)
1633
0
        {
1634
0
            p_closest = p_line;
1635
0
            p_closest_dist2 = dist2;
1636
0
        }
1637
0
        p_last = p_current;
1638
0
    }
1639
0
    else if (level < 10)
1640
0
    {
1641
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1642
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1643
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1644
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1645
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1646
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1647
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1648
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1649
0
    }
1650
0
}
1651
1652
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1653
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1654
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1655
0
{
1656
0
    IM_ASSERT(tess_tol > 0.0f);
1657
0
    ImVec2 p_last = p1;
1658
0
    ImVec2 p_closest;
1659
0
    float p_closest_dist2 = FLT_MAX;
1660
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1661
0
    return p_closest;
1662
0
}
1663
1664
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1665
0
{
1666
0
    ImVec2 ap = p - a;
1667
0
    ImVec2 ab_dir = b - a;
1668
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1669
0
    if (dot < 0.0f)
1670
0
        return a;
1671
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1672
0
    if (dot > ab_len_sqr)
1673
0
        return b;
1674
0
    return a + ab_dir * dot / ab_len_sqr;
1675
0
}
1676
1677
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1678
0
{
1679
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1680
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1681
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1682
0
    return ((b1 == b2) && (b2 == b3));
1683
0
}
1684
1685
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1686
0
{
1687
0
    ImVec2 v0 = b - a;
1688
0
    ImVec2 v1 = c - a;
1689
0
    ImVec2 v2 = p - a;
1690
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1691
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1692
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1693
0
    out_u = 1.0f - out_v - out_w;
1694
0
}
1695
1696
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1697
0
{
1698
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1699
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1700
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1701
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1702
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1703
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1704
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1705
0
    if (m == dist2_ab)
1706
0
        return proj_ab;
1707
0
    if (m == dist2_bc)
1708
0
        return proj_bc;
1709
0
    return proj_ca;
1710
0
}
1711
1712
//-----------------------------------------------------------------------------
1713
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1714
//-----------------------------------------------------------------------------
1715
1716
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1717
int ImStricmp(const char* str1, const char* str2)
1718
0
{
1719
0
    int d;
1720
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1721
0
    return d;
1722
0
}
1723
1724
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1725
0
{
1726
0
    int d = 0;
1727
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1728
0
    return d;
1729
0
}
1730
1731
void ImStrncpy(char* dst, const char* src, size_t count)
1732
0
{
1733
0
    if (count < 1)
1734
0
        return;
1735
0
    if (count > 1)
1736
0
        strncpy(dst, src, count - 1);
1737
0
    dst[count - 1] = 0;
1738
0
}
1739
1740
char* ImStrdup(const char* str)
1741
4
{
1742
4
    size_t len = strlen(str);
1743
4
    void* buf = IM_ALLOC(len + 1);
1744
4
    return (char*)memcpy(buf, (const void*)str, len + 1);
1745
4
}
1746
1747
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1748
0
{
1749
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1750
0
    size_t src_size = strlen(src) + 1;
1751
0
    if (dst_buf_size < src_size)
1752
0
    {
1753
0
        IM_FREE(dst);
1754
0
        dst = (char*)IM_ALLOC(src_size);
1755
0
        if (p_dst_size)
1756
0
            *p_dst_size = src_size;
1757
0
    }
1758
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1759
0
}
1760
1761
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1762
0
{
1763
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1764
0
    return p;
1765
0
}
1766
1767
int ImStrlenW(const ImWchar* str)
1768
0
{
1769
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1770
0
    int n = 0;
1771
0
    while (*str++) n++;
1772
0
    return n;
1773
0
}
1774
1775
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1776
const char* ImStreolRange(const char* str, const char* str_end)
1777
0
{
1778
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1779
0
    return p ? p : str_end;
1780
0
}
1781
1782
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1783
0
{
1784
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1785
0
        buf_mid_line--;
1786
0
    return buf_mid_line;
1787
0
}
1788
1789
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1790
0
{
1791
0
    if (!needle_end)
1792
0
        needle_end = needle + strlen(needle);
1793
1794
0
    const char un0 = (char)ImToUpper(*needle);
1795
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1796
0
    {
1797
0
        if (ImToUpper(*haystack) == un0)
1798
0
        {
1799
0
            const char* b = needle + 1;
1800
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1801
0
                if (ImToUpper(*a) != ImToUpper(*b))
1802
0
                    break;
1803
0
            if (b == needle_end)
1804
0
                return haystack;
1805
0
        }
1806
0
        haystack++;
1807
0
    }
1808
0
    return NULL;
1809
0
}
1810
1811
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1812
void ImStrTrimBlanks(char* buf)
1813
0
{
1814
0
    char* p = buf;
1815
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1816
0
        p++;
1817
0
    char* p_start = p;
1818
0
    while (*p != 0)                         // Find end of string
1819
0
        p++;
1820
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1821
0
        p--;
1822
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1823
0
        memmove(buf, p_start, p - p_start);
1824
0
    buf[p - p_start] = 0;                   // Zero terminate
1825
0
}
1826
1827
const char* ImStrSkipBlank(const char* str)
1828
0
{
1829
0
    while (str[0] == ' ' || str[0] == '\t')
1830
0
        str++;
1831
0
    return str;
1832
0
}
1833
1834
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1835
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1836
// B) When buf==NULL vsnprintf() will return the output size.
1837
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1838
1839
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1840
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1841
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1842
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1843
#ifdef IMGUI_USE_STB_SPRINTF
1844
#define STB_SPRINTF_IMPLEMENTATION
1845
#ifdef IMGUI_STB_SPRINTF_FILENAME
1846
#include IMGUI_STB_SPRINTF_FILENAME
1847
#else
1848
#include "stb_sprintf.h"
1849
#endif
1850
#endif
1851
1852
#if defined(_MSC_VER) && !defined(vsnprintf)
1853
#define vsnprintf _vsnprintf
1854
#endif
1855
1856
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1857
16
{
1858
16
    va_list args;
1859
16
    va_start(args, fmt);
1860
#ifdef IMGUI_USE_STB_SPRINTF
1861
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1862
#else
1863
16
    int w = vsnprintf(buf, buf_size, fmt, args);
1864
16
#endif
1865
16
    va_end(args);
1866
16
    if (buf == NULL)
1867
0
        return w;
1868
16
    if (w == -1 || w >= (int)buf_size)
1869
0
        w = (int)buf_size - 1;
1870
16
    buf[w] = 0;
1871
16
    return w;
1872
16
}
1873
1874
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1875
4.23k
{
1876
#ifdef IMGUI_USE_STB_SPRINTF
1877
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1878
#else
1879
4.23k
    int w = vsnprintf(buf, buf_size, fmt, args);
1880
4.23k
#endif
1881
4.23k
    if (buf == NULL)
1882
0
        return w;
1883
4.23k
    if (w == -1 || w >= (int)buf_size)
1884
0
        w = (int)buf_size - 1;
1885
4.23k
    buf[w] = 0;
1886
4.23k
    return w;
1887
4.23k
}
1888
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1889
1890
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1891
4.22k
{
1892
4.22k
    ImGuiContext& g = *GImGui;
1893
4.22k
    va_list args;
1894
4.22k
    va_start(args, fmt);
1895
4.22k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1896
0
    {
1897
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1898
0
        *out_buf = buf;
1899
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1900
0
    }
1901
4.22k
    else
1902
4.22k
    {
1903
4.22k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1904
4.22k
        *out_buf = g.TempBuffer.Data;
1905
4.22k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1906
4.22k
    }
1907
4.22k
    va_end(args);
1908
4.22k
}
1909
1910
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1911
30
{
1912
30
    ImGuiContext& g = *GImGui;
1913
30
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1914
15
    {
1915
15
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1916
15
        *out_buf = buf;
1917
15
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1918
15
    }
1919
15
    else
1920
15
    {
1921
15
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1922
15
        *out_buf = g.TempBuffer.Data;
1923
15
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1924
15
    }
1925
30
}
1926
1927
// CRC32 needs a 1KB lookup table (not cache friendly)
1928
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1929
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1930
static const ImU32 GCrc32LookupTable[256] =
1931
{
1932
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1933
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1934
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1935
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1936
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1937
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1938
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1939
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1940
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1941
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1942
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1943
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1944
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1945
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1946
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1947
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1948
};
1949
1950
// Known size hash
1951
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1952
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1953
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
1954
4.21k
{
1955
4.21k
    ImU32 crc = ~seed;
1956
4.21k
    const unsigned char* data = (const unsigned char*)data_p;
1957
4.21k
    const ImU32* crc32_lut = GCrc32LookupTable;
1958
21.0k
    while (data_size-- != 0)
1959
16.8k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1960
4.21k
    return ~crc;
1961
4.21k
}
1962
1963
// Zero-terminated string hash, with support for ### to reset back to seed value
1964
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
1965
// Because this syntax is rarely used we are optimizing for the common case.
1966
// - If we reach ### in the string we discard the hash so far and reset to the seed.
1967
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
1968
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1969
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
1970
128k
{
1971
128k
    seed = ~seed;
1972
128k
    ImU32 crc = seed;
1973
128k
    const unsigned char* data = (const unsigned char*)data_p;
1974
128k
    const ImU32* crc32_lut = GCrc32LookupTable;
1975
128k
    if (data_size != 0)
1976
0
    {
1977
0
        while (data_size-- != 0)
1978
0
        {
1979
0
            unsigned char c = *data++;
1980
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
1981
0
                crc = seed;
1982
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1983
0
        }
1984
0
    }
1985
128k
    else
1986
128k
    {
1987
1.77M
        while (unsigned char c = *data++)
1988
1.64M
        {
1989
1.64M
            if (c == '#' && data[0] == '#' && data[1] == '#')
1990
21.3k
                crc = seed;
1991
1.64M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1992
1.64M
        }
1993
128k
    }
1994
128k
    return ~crc;
1995
128k
}
1996
1997
//-----------------------------------------------------------------------------
1998
// [SECTION] MISC HELPERS/UTILITIES (File functions)
1999
//-----------------------------------------------------------------------------
2000
2001
// Default file functions
2002
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2003
2004
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2005
0
{
2006
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2007
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2008
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2009
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2010
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2011
    ImVector<wchar_t> buf;
2012
    buf.resize(filename_wsize + mode_wsize);
2013
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
2014
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
2015
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
2016
#else
2017
0
    return fopen(filename, mode);
2018
0
#endif
2019
0
}
2020
2021
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2022
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2023
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2024
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2025
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2026
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2027
2028
// Helper: Load file content into memory
2029
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2030
// This can't really be used with "rt" because fseek size won't match read size.
2031
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2032
0
{
2033
0
    IM_ASSERT(filename && mode);
2034
0
    if (out_file_size)
2035
0
        *out_file_size = 0;
2036
2037
0
    ImFileHandle f;
2038
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2039
0
        return NULL;
2040
2041
0
    size_t file_size = (size_t)ImFileGetSize(f);
2042
0
    if (file_size == (size_t)-1)
2043
0
    {
2044
0
        ImFileClose(f);
2045
0
        return NULL;
2046
0
    }
2047
2048
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2049
0
    if (file_data == NULL)
2050
0
    {
2051
0
        ImFileClose(f);
2052
0
        return NULL;
2053
0
    }
2054
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2055
0
    {
2056
0
        ImFileClose(f);
2057
0
        IM_FREE(file_data);
2058
0
        return NULL;
2059
0
    }
2060
0
    if (padding_bytes > 0)
2061
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2062
2063
0
    ImFileClose(f);
2064
0
    if (out_file_size)
2065
0
        *out_file_size = file_size;
2066
2067
0
    return file_data;
2068
0
}
2069
2070
//-----------------------------------------------------------------------------
2071
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2072
//-----------------------------------------------------------------------------
2073
2074
IM_MSVC_RUNTIME_CHECKS_OFF
2075
2076
// Convert UTF-8 to 32-bit character, process single character input.
2077
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2078
// We handle UTF-8 decoding error by skipping forward.
2079
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2080
11.0k
{
2081
11.0k
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2082
11.0k
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2083
11.0k
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2084
11.0k
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2085
11.0k
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2086
11.0k
    int len = lengths[*(const unsigned char*)in_text >> 3];
2087
11.0k
    int wanted = len + (len ? 0 : 1);
2088
2089
11.0k
    if (in_text_end == NULL)
2090
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2091
2092
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2093
    // so it is fast even with excessive branching.
2094
11.0k
    unsigned char s[4];
2095
11.0k
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2096
11.0k
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2097
11.0k
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2098
11.0k
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2099
2100
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2101
11.0k
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2102
11.0k
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2103
11.0k
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2104
11.0k
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2105
11.0k
    *out_char >>= shiftc[len];
2106
2107
    // Accumulate the various error conditions.
2108
11.0k
    int e = 0;
2109
11.0k
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2110
11.0k
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2111
11.0k
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2112
11.0k
    e |= (s[1] & 0xc0) >> 2;
2113
11.0k
    e |= (s[2] & 0xc0) >> 4;
2114
11.0k
    e |= (s[3]       ) >> 6;
2115
11.0k
    e ^= 0x2a; // top two bits of each tail byte correct?
2116
11.0k
    e >>= shifte[len];
2117
2118
11.0k
    if (e)
2119
297
    {
2120
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2121
        // One byte is consumed in case of invalid first byte of in_text.
2122
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2123
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2124
297
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2125
297
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2126
297
    }
2127
2128
11.0k
    return wanted;
2129
11.0k
}
2130
2131
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2132
0
{
2133
0
    ImWchar* buf_out = buf;
2134
0
    ImWchar* buf_end = buf + buf_size;
2135
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2136
0
    {
2137
0
        unsigned int c;
2138
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2139
0
        *buf_out++ = (ImWchar)c;
2140
0
    }
2141
0
    *buf_out = 0;
2142
0
    if (in_text_remaining)
2143
0
        *in_text_remaining = in_text;
2144
0
    return (int)(buf_out - buf);
2145
0
}
2146
2147
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2148
0
{
2149
0
    int char_count = 0;
2150
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2151
0
    {
2152
0
        unsigned int c;
2153
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2154
0
        char_count++;
2155
0
    }
2156
0
    return char_count;
2157
0
}
2158
2159
// Based on stb_to_utf8() from github.com/nothings/stb/
2160
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2161
0
{
2162
0
    if (c < 0x80)
2163
0
    {
2164
0
        buf[0] = (char)c;
2165
0
        return 1;
2166
0
    }
2167
0
    if (c < 0x800)
2168
0
    {
2169
0
        if (buf_size < 2) return 0;
2170
0
        buf[0] = (char)(0xc0 + (c >> 6));
2171
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2172
0
        return 2;
2173
0
    }
2174
0
    if (c < 0x10000)
2175
0
    {
2176
0
        if (buf_size < 3) return 0;
2177
0
        buf[0] = (char)(0xe0 + (c >> 12));
2178
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2179
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2180
0
        return 3;
2181
0
    }
2182
0
    if (c <= 0x10FFFF)
2183
0
    {
2184
0
        if (buf_size < 4) return 0;
2185
0
        buf[0] = (char)(0xf0 + (c >> 18));
2186
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2187
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2188
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2189
0
        return 4;
2190
0
    }
2191
    // Invalid code point, the max unicode is 0x10FFFF
2192
0
    return 0;
2193
0
}
2194
2195
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2196
0
{
2197
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2198
0
    out_buf[count] = 0;
2199
0
    return out_buf;
2200
0
}
2201
2202
// Not optimal but we very rarely use this function.
2203
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2204
0
{
2205
0
    unsigned int unused = 0;
2206
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2207
0
}
2208
2209
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2210
0
{
2211
0
    if (c < 0x80) return 1;
2212
0
    if (c < 0x800) return 2;
2213
0
    if (c < 0x10000) return 3;
2214
0
    if (c <= 0x10FFFF) return 4;
2215
0
    return 3;
2216
0
}
2217
2218
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2219
0
{
2220
0
    char* buf_p = out_buf;
2221
0
    const char* buf_end = out_buf + out_buf_size;
2222
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2223
0
    {
2224
0
        unsigned int c = (unsigned int)(*in_text++);
2225
0
        if (c < 0x80)
2226
0
            *buf_p++ = (char)c;
2227
0
        else
2228
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2229
0
    }
2230
0
    *buf_p = 0;
2231
0
    return (int)(buf_p - out_buf);
2232
0
}
2233
2234
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2235
0
{
2236
0
    int bytes_count = 0;
2237
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2238
0
    {
2239
0
        unsigned int c = (unsigned int)(*in_text++);
2240
0
        if (c < 0x80)
2241
0
            bytes_count++;
2242
0
        else
2243
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2244
0
    }
2245
0
    return bytes_count;
2246
0
}
2247
IM_MSVC_RUNTIME_CHECKS_RESTORE
2248
2249
//-----------------------------------------------------------------------------
2250
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2251
// Note: The Convert functions are early design which are not consistent with other API.
2252
//-----------------------------------------------------------------------------
2253
2254
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2255
0
{
2256
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2257
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2258
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2259
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2260
0
    return IM_COL32(r, g, b, 0xFF);
2261
0
}
2262
2263
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2264
93.1k
{
2265
93.1k
    float s = 1.0f / 255.0f;
2266
93.1k
    return ImVec4(
2267
93.1k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2268
93.1k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2269
93.1k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2270
93.1k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2271
93.1k
}
2272
2273
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2274
350k
{
2275
350k
    ImU32 out;
2276
350k
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2277
350k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2278
350k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2279
350k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2280
350k
    return out;
2281
350k
}
2282
2283
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2284
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2285
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2286
0
{
2287
0
    float K = 0.f;
2288
0
    if (g < b)
2289
0
    {
2290
0
        ImSwap(g, b);
2291
0
        K = -1.f;
2292
0
    }
2293
0
    if (r < g)
2294
0
    {
2295
0
        ImSwap(r, g);
2296
0
        K = -2.f / 6.f - K;
2297
0
    }
2298
2299
0
    const float chroma = r - (g < b ? g : b);
2300
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2301
0
    out_s = chroma / (r + 1e-20f);
2302
0
    out_v = r;
2303
0
}
2304
2305
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2306
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2307
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2308
0
{
2309
0
    if (s == 0.0f)
2310
0
    {
2311
        // gray
2312
0
        out_r = out_g = out_b = v;
2313
0
        return;
2314
0
    }
2315
2316
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2317
0
    int   i = (int)h;
2318
0
    float f = h - (float)i;
2319
0
    float p = v * (1.0f - s);
2320
0
    float q = v * (1.0f - s * f);
2321
0
    float t = v * (1.0f - s * (1.0f - f));
2322
2323
0
    switch (i)
2324
0
    {
2325
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2326
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2327
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2328
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2329
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2330
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2331
0
    }
2332
0
}
2333
2334
//-----------------------------------------------------------------------------
2335
// [SECTION] ImGuiStorage
2336
// Helper: Key->value storage
2337
//-----------------------------------------------------------------------------
2338
2339
// std::lower_bound but without the bullshit
2340
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2341
46.9k
{
2342
46.9k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2343
46.9k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2344
46.9k
    size_t count = (size_t)(last - first);
2345
163k
    while (count > 0)
2346
116k
    {
2347
116k
        size_t count2 = count >> 1;
2348
116k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2349
116k
        if (mid->key < key)
2350
25.6k
        {
2351
25.6k
            first = ++mid;
2352
25.6k
            count -= count2 + 1;
2353
25.6k
        }
2354
91.3k
        else
2355
91.3k
        {
2356
91.3k
            count = count2;
2357
91.3k
        }
2358
116k
    }
2359
46.9k
    return first;
2360
46.9k
}
2361
2362
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2363
void ImGuiStorage::BuildSortByKey()
2364
0
{
2365
0
    struct StaticFunc
2366
0
    {
2367
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2368
0
        {
2369
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2370
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2371
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2372
0
            return 0;
2373
0
        }
2374
0
    };
2375
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2376
0
}
2377
2378
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2379
0
{
2380
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2381
0
    if (it == Data.end() || it->key != key)
2382
0
        return default_val;
2383
0
    return it->val_i;
2384
0
}
2385
2386
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2387
0
{
2388
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2389
0
}
2390
2391
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2392
0
{
2393
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2394
0
    if (it == Data.end() || it->key != key)
2395
0
        return default_val;
2396
0
    return it->val_f;
2397
0
}
2398
2399
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2400
46.9k
{
2401
46.9k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2402
46.9k
    if (it == Data.end() || it->key != key)
2403
4
        return NULL;
2404
46.9k
    return it->val_p;
2405
46.9k
}
2406
2407
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2408
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2409
0
{
2410
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2411
0
    if (it == Data.end() || it->key != key)
2412
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2413
0
    return &it->val_i;
2414
0
}
2415
2416
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2417
0
{
2418
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2419
0
}
2420
2421
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2422
0
{
2423
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2424
0
    if (it == Data.end() || it->key != key)
2425
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2426
0
    return &it->val_f;
2427
0
}
2428
2429
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2430
0
{
2431
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2432
0
    if (it == Data.end() || it->key != key)
2433
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2434
0
    return &it->val_p;
2435
0
}
2436
2437
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2438
void ImGuiStorage::SetInt(ImGuiID key, int val)
2439
0
{
2440
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2441
0
    if (it == Data.end() || it->key != key)
2442
0
    {
2443
0
        Data.insert(it, ImGuiStoragePair(key, val));
2444
0
        return;
2445
0
    }
2446
0
    it->val_i = val;
2447
0
}
2448
2449
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2450
0
{
2451
0
    SetInt(key, val ? 1 : 0);
2452
0
}
2453
2454
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2455
0
{
2456
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2457
0
    if (it == Data.end() || it->key != key)
2458
0
    {
2459
0
        Data.insert(it, ImGuiStoragePair(key, val));
2460
0
        return;
2461
0
    }
2462
0
    it->val_f = val;
2463
0
}
2464
2465
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2466
4
{
2467
4
    ImGuiStoragePair* it = LowerBound(Data, key);
2468
4
    if (it == Data.end() || it->key != key)
2469
4
    {
2470
4
        Data.insert(it, ImGuiStoragePair(key, val));
2471
4
        return;
2472
4
    }
2473
0
    it->val_p = val;
2474
0
}
2475
2476
void ImGuiStorage::SetAllInt(int v)
2477
0
{
2478
0
    for (int i = 0; i < Data.Size; i++)
2479
0
        Data[i].val_i = v;
2480
0
}
2481
2482
//-----------------------------------------------------------------------------
2483
// [SECTION] ImGuiTextFilter
2484
//-----------------------------------------------------------------------------
2485
2486
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2487
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2488
0
{
2489
0
    InputBuf[0] = 0;
2490
0
    CountGrep = 0;
2491
0
    if (default_filter)
2492
0
    {
2493
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2494
0
        Build();
2495
0
    }
2496
0
}
2497
2498
bool ImGuiTextFilter::Draw(const char* label, float width)
2499
0
{
2500
0
    if (width != 0.0f)
2501
0
        ImGui::SetNextItemWidth(width);
2502
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2503
0
    if (value_changed)
2504
0
        Build();
2505
0
    return value_changed;
2506
0
}
2507
2508
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2509
0
{
2510
0
    out->resize(0);
2511
0
    const char* wb = b;
2512
0
    const char* we = wb;
2513
0
    while (we < e)
2514
0
    {
2515
0
        if (*we == separator)
2516
0
        {
2517
0
            out->push_back(ImGuiTextRange(wb, we));
2518
0
            wb = we + 1;
2519
0
        }
2520
0
        we++;
2521
0
    }
2522
0
    if (wb != we)
2523
0
        out->push_back(ImGuiTextRange(wb, we));
2524
0
}
2525
2526
void ImGuiTextFilter::Build()
2527
0
{
2528
0
    Filters.resize(0);
2529
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2530
0
    input_range.split(',', &Filters);
2531
2532
0
    CountGrep = 0;
2533
0
    for (int i = 0; i != Filters.Size; i++)
2534
0
    {
2535
0
        ImGuiTextRange& f = Filters[i];
2536
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2537
0
            f.b++;
2538
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2539
0
            f.e--;
2540
0
        if (f.empty())
2541
0
            continue;
2542
0
        if (Filters[i].b[0] != '-')
2543
0
            CountGrep += 1;
2544
0
    }
2545
0
}
2546
2547
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2548
0
{
2549
0
    if (Filters.empty())
2550
0
        return true;
2551
2552
0
    if (text == NULL)
2553
0
        text = "";
2554
2555
0
    for (int i = 0; i != Filters.Size; i++)
2556
0
    {
2557
0
        const ImGuiTextRange& f = Filters[i];
2558
0
        if (f.empty())
2559
0
            continue;
2560
0
        if (f.b[0] == '-')
2561
0
        {
2562
            // Subtract
2563
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2564
0
                return false;
2565
0
        }
2566
0
        else
2567
0
        {
2568
            // Grep
2569
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2570
0
                return true;
2571
0
        }
2572
0
    }
2573
2574
    // Implicit * grep
2575
0
    if (CountGrep == 0)
2576
0
        return true;
2577
2578
0
    return false;
2579
0
}
2580
2581
//-----------------------------------------------------------------------------
2582
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2583
//-----------------------------------------------------------------------------
2584
2585
// On some platform vsnprintf() takes va_list by reference and modifies it.
2586
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2587
#ifndef va_copy
2588
#if defined(__GNUC__) || defined(__clang__)
2589
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2590
#else
2591
#define va_copy(dest, src) (dest = src)
2592
#endif
2593
#endif
2594
2595
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2596
2597
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2598
0
{
2599
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2600
2601
    // Add zero-terminator the first time
2602
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2603
0
    const int needed_sz = write_off + len;
2604
0
    if (write_off + len >= Buf.Capacity)
2605
0
    {
2606
0
        int new_capacity = Buf.Capacity * 2;
2607
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2608
0
    }
2609
2610
0
    Buf.resize(needed_sz);
2611
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2612
0
    Buf[write_off - 1 + len] = 0;
2613
0
}
2614
2615
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2616
0
{
2617
0
    va_list args;
2618
0
    va_start(args, fmt);
2619
0
    appendfv(fmt, args);
2620
0
    va_end(args);
2621
0
}
2622
2623
// Helper: Text buffer for logging/accumulating text
2624
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2625
0
{
2626
0
    va_list args_copy;
2627
0
    va_copy(args_copy, args);
2628
2629
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2630
0
    if (len <= 0)
2631
0
    {
2632
0
        va_end(args_copy);
2633
0
        return;
2634
0
    }
2635
2636
    // Add zero-terminator the first time
2637
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2638
0
    const int needed_sz = write_off + len;
2639
0
    if (write_off + len >= Buf.Capacity)
2640
0
    {
2641
0
        int new_capacity = Buf.Capacity * 2;
2642
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2643
0
    }
2644
2645
0
    Buf.resize(needed_sz);
2646
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2647
0
    va_end(args_copy);
2648
0
}
2649
2650
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2651
0
{
2652
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2653
0
    if (old_size == new_size)
2654
0
        return;
2655
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2656
0
        LineOffsets.push_back(EndOffset);
2657
0
    const char* base_end = base + new_size;
2658
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2659
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2660
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2661
0
    EndOffset = ImMax(EndOffset, new_size);
2662
0
}
2663
2664
//-----------------------------------------------------------------------------
2665
// [SECTION] ImGuiListClipper
2666
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
2667
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
2668
//-----------------------------------------------------------------------------
2669
2670
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2671
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2672
static bool GetSkipItemForListClipping()
2673
0
{
2674
0
    ImGuiContext& g = *GImGui;
2675
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2676
0
}
2677
2678
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2679
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2680
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2681
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2682
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2683
{
2684
    ImGuiContext& g = *GImGui;
2685
    ImGuiWindow* window = g.CurrentWindow;
2686
    if (g.LogEnabled)
2687
    {
2688
        // If logging is active, do not perform any clipping
2689
        *out_items_display_start = 0;
2690
        *out_items_display_end = items_count;
2691
        return;
2692
    }
2693
    if (GetSkipItemForListClipping())
2694
    {
2695
        *out_items_display_start = *out_items_display_end = 0;
2696
        return;
2697
    }
2698
2699
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2700
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2701
    ImRect rect = window->ClipRect;
2702
    if (g.NavMoveScoringItems)
2703
        rect.Add(g.NavScoringNoClipRect);
2704
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2705
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2706
2707
    const ImVec2 pos = window->DC.CursorPos;
2708
    int start = (int)((rect.Min.y - pos.y) / items_height);
2709
    int end = (int)((rect.Max.y - pos.y) / items_height);
2710
2711
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2712
    // FIXME: Verify this works with tabbing
2713
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2714
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2715
        start--;
2716
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2717
        end++;
2718
2719
    start = ImClamp(start, 0, items_count);
2720
    end = ImClamp(end + 1, start, items_count);
2721
    *out_items_display_start = start;
2722
    *out_items_display_end = end;
2723
}
2724
#endif
2725
2726
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2727
0
{
2728
0
    if (ranges.Size - offset <= 1)
2729
0
        return;
2730
2731
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2732
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2733
0
        for (int i = offset; i < sort_end + offset; ++i)
2734
0
            if (ranges[i].Min > ranges[i + 1].Min)
2735
0
                ImSwap(ranges[i], ranges[i + 1]);
2736
2737
    // Now fuse ranges together as much as possible.
2738
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2739
0
    {
2740
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2741
0
        if (ranges[i - 1].Max < ranges[i].Min)
2742
0
            continue;
2743
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2744
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2745
0
        ranges.erase(ranges.Data + i);
2746
0
        i--;
2747
0
    }
2748
0
}
2749
2750
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2751
0
{
2752
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2753
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2754
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2755
0
    ImGuiContext& g = *GImGui;
2756
0
    ImGuiWindow* window = g.CurrentWindow;
2757
0
    float off_y = pos_y - window->DC.CursorPos.y;
2758
0
    window->DC.CursorPos.y = pos_y;
2759
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2760
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2761
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2762
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2763
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2764
0
    if (ImGuiTable* table = g.CurrentTable)
2765
0
    {
2766
0
        if (table->IsInsideRow)
2767
0
            ImGui::TableEndRow(table);
2768
0
        table->RowPosY2 = window->DC.CursorPos.y;
2769
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2770
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2771
0
        table->RowBgColorCounter += row_increase;
2772
0
    }
2773
0
}
2774
2775
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2776
0
{
2777
    // StartPosY starts from ItemsFrozen hence the subtraction
2778
    // Perform the add and multiply with double to allow seeking through larger ranges
2779
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2780
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2781
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2782
0
}
2783
2784
ImGuiListClipper::ImGuiListClipper()
2785
0
{
2786
0
    memset(this, 0, sizeof(*this));
2787
0
    Ctx = ImGui::GetCurrentContext();
2788
0
    IM_ASSERT(Ctx != NULL);
2789
0
    ItemsCount = -1;
2790
0
}
2791
2792
ImGuiListClipper::~ImGuiListClipper()
2793
0
{
2794
0
    End();
2795
0
}
2796
2797
void ImGuiListClipper::Begin(int items_count, float items_height)
2798
0
{
2799
0
    ImGuiContext& g = *Ctx;
2800
0
    ImGuiWindow* window = g.CurrentWindow;
2801
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2802
2803
0
    if (ImGuiTable* table = g.CurrentTable)
2804
0
        if (table->IsInsideRow)
2805
0
            ImGui::TableEndRow(table);
2806
2807
0
    StartPosY = window->DC.CursorPos.y;
2808
0
    ItemsHeight = items_height;
2809
0
    ItemsCount = items_count;
2810
0
    DisplayStart = -1;
2811
0
    DisplayEnd = 0;
2812
2813
    // Acquire temporary buffer
2814
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2815
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2816
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2817
0
    data->Reset(this);
2818
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2819
0
    TempData = data;
2820
0
}
2821
2822
void ImGuiListClipper::End()
2823
0
{
2824
0
    ImGuiContext& g = *Ctx;
2825
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2826
0
    {
2827
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2828
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2829
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2830
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2831
2832
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2833
0
        IM_ASSERT(data->ListClipper == this);
2834
0
        data->StepNo = data->Ranges.Size;
2835
0
        if (--g.ClipperTempDataStacked > 0)
2836
0
        {
2837
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2838
0
            data->ListClipper->TempData = data;
2839
0
        }
2840
0
        TempData = NULL;
2841
0
    }
2842
0
    ItemsCount = -1;
2843
0
}
2844
2845
void ImGuiListClipper::ForceDisplayRangeByIndices(int item_min, int item_max)
2846
0
{
2847
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2848
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2849
0
    IM_ASSERT(item_min <= item_max);
2850
0
    if (item_min < item_max)
2851
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_min, item_max));
2852
0
}
2853
2854
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2855
0
{
2856
0
    ImGuiContext& g = *clipper->Ctx;
2857
0
    ImGuiWindow* window = g.CurrentWindow;
2858
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2859
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2860
2861
0
    ImGuiTable* table = g.CurrentTable;
2862
0
    if (table && table->IsInsideRow)
2863
0
        ImGui::TableEndRow(table);
2864
2865
    // No items
2866
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2867
0
        return false;
2868
2869
    // While we are in frozen row state, keep displaying items one by one, unclipped
2870
    // FIXME: Could be stored as a table-agnostic state.
2871
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2872
0
    {
2873
0
        clipper->DisplayStart = data->ItemsFrozen;
2874
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2875
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2876
0
            data->ItemsFrozen++;
2877
0
        return true;
2878
0
    }
2879
2880
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2881
0
    bool calc_clipping = false;
2882
0
    if (data->StepNo == 0)
2883
0
    {
2884
0
        clipper->StartPosY = window->DC.CursorPos.y;
2885
0
        if (clipper->ItemsHeight <= 0.0f)
2886
0
        {
2887
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2888
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2889
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2890
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2891
0
            data->StepNo = 1;
2892
0
            return true;
2893
0
        }
2894
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2895
0
    }
2896
2897
    // Step 1: Let the clipper infer height from first range
2898
0
    if (clipper->ItemsHeight <= 0.0f)
2899
0
    {
2900
0
        IM_ASSERT(data->StepNo == 1);
2901
0
        if (table)
2902
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2903
2904
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2905
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2906
0
        if (affected_by_floating_point_precision)
2907
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2908
2909
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2910
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
2911
0
    }
2912
2913
    // Step 0 or 1: Calculate the actual ranges of visible elements.
2914
0
    const int already_submitted = clipper->DisplayEnd;
2915
0
    if (calc_clipping)
2916
0
    {
2917
0
        if (g.LogEnabled)
2918
0
        {
2919
            // If logging is active, do not perform any clipping
2920
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2921
0
        }
2922
0
        else
2923
0
        {
2924
            // Add range selected to be included for navigation
2925
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2926
0
            if (is_nav_request)
2927
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
2928
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)
2929
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
2930
2931
            // Add focused/active item
2932
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
2933
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
2934
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
2935
2936
            // Add visible range
2937
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
2938
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
2939
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
2940
0
        }
2941
2942
        // Convert position ranges to item index ranges
2943
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
2944
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
2945
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
2946
0
        for (int i = 0; i < data->Ranges.Size; i++)
2947
0
            if (data->Ranges[i].PosToIndexConvert)
2948
0
            {
2949
0
                int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
2950
0
                int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
2951
0
                data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
2952
0
                data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, clipper->ItemsCount);
2953
0
                data->Ranges[i].PosToIndexConvert = false;
2954
0
            }
2955
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
2956
0
    }
2957
2958
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
2959
0
    if (data->StepNo < data->Ranges.Size)
2960
0
    {
2961
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
2962
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
2963
0
        if (clipper->DisplayStart > already_submitted) //-V1051
2964
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
2965
0
        data->StepNo++;
2966
0
        return true;
2967
0
    }
2968
2969
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
2970
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
2971
0
    if (clipper->ItemsCount < INT_MAX)
2972
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
2973
2974
0
    return false;
2975
0
}
2976
2977
bool ImGuiListClipper::Step()
2978
0
{
2979
0
    ImGuiContext& g = *Ctx;
2980
0
    bool need_items_height = (ItemsHeight <= 0.0f);
2981
0
    bool ret = ImGuiListClipper_StepInternal(this);
2982
0
    if (ret && (DisplayStart == DisplayEnd))
2983
0
        ret = false;
2984
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
2985
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
2986
0
    if (need_items_height && ItemsHeight > 0.0f)
2987
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
2988
0
    if (ret)
2989
0
    {
2990
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
2991
0
    }
2992
0
    else
2993
0
    {
2994
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
2995
0
        End();
2996
0
    }
2997
0
    return ret;
2998
0
}
2999
3000
//-----------------------------------------------------------------------------
3001
// [SECTION] STYLING
3002
//-----------------------------------------------------------------------------
3003
3004
ImGuiStyle& ImGui::GetStyle()
3005
71.8k
{
3006
71.8k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3007
71.8k
    return GImGui->Style;
3008
71.8k
}
3009
3010
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3011
279k
{
3012
279k
    ImGuiStyle& style = GImGui->Style;
3013
279k
    ImVec4 c = style.Colors[idx];
3014
279k
    c.w *= style.Alpha * alpha_mul;
3015
279k
    return ColorConvertFloat4ToU32(c);
3016
279k
}
3017
3018
ImU32 ImGui::GetColorU32(const ImVec4& col)
3019
0
{
3020
0
    ImGuiStyle& style = GImGui->Style;
3021
0
    ImVec4 c = col;
3022
0
    c.w *= style.Alpha;
3023
0
    return ColorConvertFloat4ToU32(c);
3024
0
}
3025
3026
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3027
0
{
3028
0
    ImGuiStyle& style = GImGui->Style;
3029
0
    return style.Colors[idx];
3030
0
}
3031
3032
ImU32 ImGui::GetColorU32(ImU32 col)
3033
0
{
3034
0
    ImGuiStyle& style = GImGui->Style;
3035
0
    if (style.Alpha >= 1.0f)
3036
0
        return col;
3037
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3038
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3039
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3040
0
}
3041
3042
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3043
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3044
0
{
3045
0
    ImGuiContext& g = *GImGui;
3046
0
    ImGuiColorMod backup;
3047
0
    backup.Col = idx;
3048
0
    backup.BackupValue = g.Style.Colors[idx];
3049
0
    g.ColorStack.push_back(backup);
3050
0
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3051
0
}
3052
3053
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3054
21.3k
{
3055
21.3k
    ImGuiContext& g = *GImGui;
3056
21.3k
    ImGuiColorMod backup;
3057
21.3k
    backup.Col = idx;
3058
21.3k
    backup.BackupValue = g.Style.Colors[idx];
3059
21.3k
    g.ColorStack.push_back(backup);
3060
21.3k
    g.Style.Colors[idx] = col;
3061
21.3k
}
3062
3063
void ImGui::PopStyleColor(int count)
3064
21.3k
{
3065
21.3k
    ImGuiContext& g = *GImGui;
3066
21.3k
    if (g.ColorStack.Size < count)
3067
0
    {
3068
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3069
0
        count = g.ColorStack.Size;
3070
0
    }
3071
42.7k
    while (count > 0)
3072
21.3k
    {
3073
21.3k
        ImGuiColorMod& backup = g.ColorStack.back();
3074
21.3k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3075
21.3k
        g.ColorStack.pop_back();
3076
21.3k
        count--;
3077
21.3k
    }
3078
21.3k
}
3079
3080
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3081
{
3082
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3083
};
3084
3085
static const ImGuiDataVarInfo GStyleVarInfo[] =
3086
{
3087
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
3088
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
3089
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
3090
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
3091
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
3092
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
3093
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
3094
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
3095
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
3096
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
3097
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
3098
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
3099
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
3100
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
3101
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
3102
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
3103
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
3104
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
3105
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
3106
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
3107
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
3108
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
3109
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
3110
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
3111
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3112
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3113
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextAlign) },     // ImGuiStyleVar_SeparatorTextAlign
3114
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextPadding) },   // ImGuiStyleVar_SeparatorTextPadding
3115
};
3116
3117
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3118
42.7k
{
3119
42.7k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3120
42.7k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3121
42.7k
    return &GStyleVarInfo[idx];
3122
42.7k
}
3123
3124
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3125
0
{
3126
0
    ImGuiContext& g = *GImGui;
3127
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3128
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3129
0
    {
3130
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3131
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3132
0
        *pvar = val;
3133
0
        return;
3134
0
    }
3135
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3136
0
}
3137
3138
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3139
21.3k
{
3140
21.3k
    ImGuiContext& g = *GImGui;
3141
21.3k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3142
21.3k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3143
21.3k
    {
3144
21.3k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3145
21.3k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3146
21.3k
        *pvar = val;
3147
21.3k
        return;
3148
21.3k
    }
3149
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3150
0
}
3151
3152
void ImGui::PopStyleVar(int count)
3153
21.3k
{
3154
21.3k
    ImGuiContext& g = *GImGui;
3155
21.3k
    if (g.StyleVarStack.Size < count)
3156
0
    {
3157
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3158
0
        count = g.StyleVarStack.Size;
3159
0
    }
3160
42.7k
    while (count > 0)
3161
21.3k
    {
3162
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3163
21.3k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3164
21.3k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3165
21.3k
        void* data = info->GetVarPtr(&g.Style);
3166
21.3k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3167
21.3k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3168
21.3k
        g.StyleVarStack.pop_back();
3169
21.3k
        count--;
3170
21.3k
    }
3171
21.3k
}
3172
3173
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3174
0
{
3175
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3176
0
    switch (idx)
3177
0
    {
3178
0
    case ImGuiCol_Text: return "Text";
3179
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3180
0
    case ImGuiCol_WindowBg: return "WindowBg";
3181
0
    case ImGuiCol_ChildBg: return "ChildBg";
3182
0
    case ImGuiCol_PopupBg: return "PopupBg";
3183
0
    case ImGuiCol_Border: return "Border";
3184
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3185
0
    case ImGuiCol_FrameBg: return "FrameBg";
3186
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3187
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3188
0
    case ImGuiCol_TitleBg: return "TitleBg";
3189
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3190
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3191
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3192
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3193
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3194
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3195
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3196
0
    case ImGuiCol_CheckMark: return "CheckMark";
3197
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3198
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3199
0
    case ImGuiCol_Button: return "Button";
3200
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3201
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3202
0
    case ImGuiCol_Header: return "Header";
3203
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3204
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3205
0
    case ImGuiCol_Separator: return "Separator";
3206
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3207
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3208
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3209
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3210
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3211
0
    case ImGuiCol_Tab: return "Tab";
3212
0
    case ImGuiCol_TabHovered: return "TabHovered";
3213
0
    case ImGuiCol_TabActive: return "TabActive";
3214
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3215
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3216
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3217
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3218
0
    case ImGuiCol_PlotLines: return "PlotLines";
3219
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3220
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3221
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3222
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3223
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3224
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3225
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3226
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3227
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3228
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3229
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3230
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3231
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3232
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3233
0
    }
3234
0
    IM_ASSERT(0);
3235
0
    return "Unknown";
3236
0
}
3237
3238
3239
//-----------------------------------------------------------------------------
3240
// [SECTION] RENDER HELPERS
3241
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3242
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3243
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3244
//-----------------------------------------------------------------------------
3245
3246
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3247
85.4k
{
3248
85.4k
    const char* text_display_end = text;
3249
85.4k
    if (!text_end)
3250
85.4k
        text_end = (const char*)-1;
3251
3252
769k
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3253
683k
        text_display_end++;
3254
85.4k
    return text_display_end;
3255
85.4k
}
3256
3257
// Internal ImGui functions to render text
3258
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3259
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3260
0
{
3261
0
    ImGuiContext& g = *GImGui;
3262
0
    ImGuiWindow* window = g.CurrentWindow;
3263
3264
    // Hide anything after a '##' string
3265
0
    const char* text_display_end;
3266
0
    if (hide_text_after_hash)
3267
0
    {
3268
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3269
0
    }
3270
0
    else
3271
0
    {
3272
0
        if (!text_end)
3273
0
            text_end = text + strlen(text); // FIXME-OPT
3274
0
        text_display_end = text_end;
3275
0
    }
3276
3277
0
    if (text != text_display_end)
3278
0
    {
3279
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3280
0
        if (g.LogEnabled)
3281
0
            LogRenderedText(&pos, text, text_display_end);
3282
0
    }
3283
0
}
3284
3285
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3286
18
{
3287
18
    ImGuiContext& g = *GImGui;
3288
18
    ImGuiWindow* window = g.CurrentWindow;
3289
3290
18
    if (!text_end)
3291
0
        text_end = text + strlen(text); // FIXME-OPT
3292
3293
18
    if (text != text_end)
3294
18
    {
3295
18
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3296
18
        if (g.LogEnabled)
3297
0
            LogRenderedText(&pos, text, text_end);
3298
18
    }
3299
18
}
3300
3301
// Default clip_rect uses (pos_min,pos_max)
3302
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3303
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3304
42.7k
{
3305
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3306
42.7k
    ImVec2 pos = pos_min;
3307
42.7k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3308
3309
42.7k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3310
42.7k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3311
42.7k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3312
42.7k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3313
42.7k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3314
3315
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3316
42.7k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3317
42.7k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3318
3319
    // Render
3320
42.7k
    if (need_clipping)
3321
1
    {
3322
1
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3323
1
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3324
1
    }
3325
42.7k
    else
3326
42.7k
    {
3327
42.7k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3328
42.7k
    }
3329
42.7k
}
3330
3331
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3332
42.7k
{
3333
    // Hide anything after a '##' string
3334
42.7k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3335
42.7k
    const int text_len = (int)(text_display_end - text);
3336
42.7k
    if (text_len == 0)
3337
0
        return;
3338
3339
42.7k
    ImGuiContext& g = *GImGui;
3340
42.7k
    ImGuiWindow* window = g.CurrentWindow;
3341
42.7k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3342
42.7k
    if (g.LogEnabled)
3343
0
        LogRenderedText(&pos_min, text, text_display_end);
3344
42.7k
}
3345
3346
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3347
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3348
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3349
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3350
0
{
3351
0
    ImGuiContext& g = *GImGui;
3352
0
    if (text_end_full == NULL)
3353
0
        text_end_full = FindRenderedTextEnd(text);
3354
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3355
3356
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3357
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3358
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3359
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3360
0
    if (text_size.x > pos_max.x - pos_min.x)
3361
0
    {
3362
        // Hello wo...
3363
        // |       |   |
3364
        // min   max   ellipsis_max
3365
        //          <-> this is generally some padding value
3366
3367
0
        const ImFont* font = draw_list->_Data->Font;
3368
0
        const float font_size = draw_list->_Data->FontSize;
3369
0
        const float font_scale = font_size / font->FontSize;
3370
0
        const char* text_end_ellipsis = NULL;
3371
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3372
3373
        // We can now claim the space between pos_max.x and ellipsis_max.x
3374
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3375
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3376
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3377
0
        {
3378
            // Always display at least 1 character if there's no room for character + ellipsis
3379
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3380
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3381
0
        }
3382
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3383
0
        {
3384
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3385
0
            text_end_ellipsis--;
3386
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3387
0
        }
3388
3389
        // Render text, render ellipsis
3390
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3391
0
        ImVec2 ellipsis_pos = ImFloor(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3392
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3393
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3394
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3395
0
    }
3396
0
    else
3397
0
    {
3398
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3399
0
    }
3400
3401
0
    if (g.LogEnabled)
3402
0
        LogRenderedText(&pos_min, text, text_end_full);
3403
0
}
3404
3405
// Render a rectangle shaped with optional rounding and borders
3406
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3407
17.1k
{
3408
17.1k
    ImGuiContext& g = *GImGui;
3409
17.1k
    ImGuiWindow* window = g.CurrentWindow;
3410
17.1k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3411
17.1k
    const float border_size = g.Style.FrameBorderSize;
3412
17.1k
    if (border && border_size > 0.0f)
3413
17.1k
    {
3414
17.1k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3415
17.1k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3416
17.1k
    }
3417
17.1k
}
3418
3419
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3420
0
{
3421
0
    ImGuiContext& g = *GImGui;
3422
0
    ImGuiWindow* window = g.CurrentWindow;
3423
0
    const float border_size = g.Style.FrameBorderSize;
3424
0
    if (border_size > 0.0f)
3425
0
    {
3426
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3427
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3428
0
    }
3429
0
}
3430
3431
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3432
6.57k
{
3433
6.57k
    ImGuiContext& g = *GImGui;
3434
6.57k
    if (id != g.NavId)
3435
3.66k
        return;
3436
2.91k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3437
1.07k
        return;
3438
1.83k
    ImGuiWindow* window = g.CurrentWindow;
3439
1.83k
    if (window->DC.NavHideHighlightOneFrame)
3440
0
        return;
3441
3442
1.83k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3443
1.83k
    ImRect display_rect = bb;
3444
1.83k
    display_rect.ClipWith(window->ClipRect);
3445
1.83k
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3446
37
    {
3447
37
        const float THICKNESS = 2.0f;
3448
37
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3449
37
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3450
37
        bool fully_visible = window->ClipRect.Contains(display_rect);
3451
37
        if (!fully_visible)
3452
3
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3453
37
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3454
37
        if (!fully_visible)
3455
3
            window->DrawList->PopClipRect();
3456
37
    }
3457
1.83k
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3458
1.79k
    {
3459
1.79k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3460
1.79k
    }
3461
1.83k
}
3462
3463
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3464
0
{
3465
0
    ImGuiContext& g = *GImGui;
3466
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3467
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3468
0
    for (int n = 0; n < g.Viewports.Size; n++)
3469
0
    {
3470
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3471
0
        ImVec2 offset, size, uv[4];
3472
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3473
0
            continue;
3474
0
        ImGuiViewportP* viewport = g.Viewports[n];
3475
0
        const ImVec2 pos = base_pos - offset;
3476
0
        const float scale = base_scale * viewport->DpiScale;
3477
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3478
0
            continue;
3479
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3480
0
        ImTextureID tex_id = font_atlas->TexID;
3481
0
        draw_list->PushTextureID(tex_id);
3482
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3483
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3484
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3485
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3486
0
        draw_list->PopTextureID();
3487
0
    }
3488
0
}
3489
3490
//-----------------------------------------------------------------------------
3491
// [SECTION] INITIALIZATION, SHUTDOWN
3492
//-----------------------------------------------------------------------------
3493
3494
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3495
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3496
ImGuiContext* ImGui::GetCurrentContext()
3497
1
{
3498
1
    return GImGui;
3499
1
}
3500
3501
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3502
1
{
3503
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3504
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3505
#else
3506
1
    GImGui = ctx;
3507
1
#endif
3508
1
}
3509
3510
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3511
0
{
3512
0
    GImAllocatorAllocFunc = alloc_func;
3513
0
    GImAllocatorFreeFunc = free_func;
3514
0
    GImAllocatorUserData = user_data;
3515
0
}
3516
3517
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3518
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3519
0
{
3520
0
    *p_alloc_func = GImAllocatorAllocFunc;
3521
0
    *p_free_func = GImAllocatorFreeFunc;
3522
0
    *p_user_data = GImAllocatorUserData;
3523
0
}
3524
3525
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3526
1
{
3527
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3528
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3529
1
    SetCurrentContext(ctx);
3530
1
    Initialize();
3531
1
    if (prev_ctx != NULL)
3532
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3533
1
    return ctx;
3534
1
}
3535
3536
void ImGui::DestroyContext(ImGuiContext* ctx)
3537
0
{
3538
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3539
0
    if (ctx == NULL) //-V1051
3540
0
        ctx = prev_ctx;
3541
0
    SetCurrentContext(ctx);
3542
0
    Shutdown();
3543
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3544
0
    IM_DELETE(ctx);
3545
0
}
3546
3547
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3548
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3549
{
3550
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3551
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3552
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3553
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3554
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3555
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3556
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3557
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3558
};
3559
3560
void ImGui::Initialize()
3561
1
{
3562
1
    ImGuiContext& g = *GImGui;
3563
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3564
3565
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3566
1
    {
3567
1
        ImGuiSettingsHandler ini_handler;
3568
1
        ini_handler.TypeName = "Window";
3569
1
        ini_handler.TypeHash = ImHashStr("Window");
3570
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3571
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3572
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3573
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3574
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3575
1
        AddSettingsHandler(&ini_handler);
3576
1
    }
3577
1
    TableSettingsAddSettingsHandler();
3578
3579
    // Setup default localization table
3580
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3581
3582
    // Setup default platform clipboard/IME handlers.
3583
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3584
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3585
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3586
1
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3587
3588
    // Create default viewport
3589
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3590
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3591
1
    viewport->Idx = 0;
3592
1
    viewport->PlatformWindowCreated = true;
3593
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3594
1
    g.Viewports.push_back(viewport);
3595
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3596
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3597
3598
1
#ifdef IMGUI_HAS_DOCK
3599
    // Initialize Docking
3600
1
    DockContextInitialize(&g);
3601
1
#endif
3602
3603
1
    g.Initialized = true;
3604
1
}
3605
3606
// This function is merely here to free heap allocations.
3607
void ImGui::Shutdown()
3608
0
{
3609
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3610
0
    ImGuiContext& g = *GImGui;
3611
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3612
0
    {
3613
0
        g.IO.Fonts->Locked = false;
3614
0
        IM_DELETE(g.IO.Fonts);
3615
0
    }
3616
0
    g.IO.Fonts = NULL;
3617
0
    g.DrawListSharedData.TempBuffer.clear();
3618
3619
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3620
0
    if (!g.Initialized)
3621
0
        return;
3622
3623
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3624
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3625
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3626
3627
    // Destroy platform windows
3628
0
    DestroyPlatformWindows();
3629
3630
    // Shutdown extensions
3631
0
    DockContextShutdown(&g);
3632
3633
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3634
3635
    // Clear everything else
3636
0
    g.Windows.clear_delete();
3637
0
    g.WindowsFocusOrder.clear();
3638
0
    g.WindowsTempSortBuffer.clear();
3639
0
    g.CurrentWindow = NULL;
3640
0
    g.CurrentWindowStack.clear();
3641
0
    g.WindowsById.Clear();
3642
0
    g.NavWindow = NULL;
3643
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3644
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3645
0
    g.MovingWindow = NULL;
3646
3647
0
    g.KeysRoutingTable.Clear();
3648
3649
0
    g.ColorStack.clear();
3650
0
    g.StyleVarStack.clear();
3651
0
    g.FontStack.clear();
3652
0
    g.OpenPopupStack.clear();
3653
0
    g.BeginPopupStack.clear();
3654
3655
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3656
0
    g.Viewports.clear_delete();
3657
3658
0
    g.TabBars.Clear();
3659
0
    g.CurrentTabBarStack.clear();
3660
0
    g.ShrinkWidthBuffer.clear();
3661
3662
0
    g.ClipperTempData.clear_destruct();
3663
3664
0
    g.Tables.Clear();
3665
0
    g.TablesTempData.clear_destruct();
3666
0
    g.DrawChannelsTempMergeBuffer.clear();
3667
3668
0
    g.ClipboardHandlerData.clear();
3669
0
    g.MenusIdSubmittedThisFrame.clear();
3670
0
    g.InputTextState.ClearFreeMemory();
3671
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3672
3673
0
    g.SettingsWindows.clear();
3674
0
    g.SettingsHandlers.clear();
3675
3676
0
    if (g.LogFile)
3677
0
    {
3678
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3679
0
        if (g.LogFile != stdout)
3680
0
#endif
3681
0
            ImFileClose(g.LogFile);
3682
0
        g.LogFile = NULL;
3683
0
    }
3684
0
    g.LogBuffer.clear();
3685
0
    g.DebugLogBuf.clear();
3686
0
    g.DebugLogIndex.clear();
3687
3688
0
    g.Initialized = false;
3689
0
}
3690
3691
// No specific ordering/dependency support, will see as needed
3692
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3693
0
{
3694
0
    ImGuiContext& g = *ctx;
3695
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3696
0
    g.Hooks.push_back(*hook);
3697
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3698
0
    return g.HookIdNext;
3699
0
}
3700
3701
// Deferred removal, avoiding issue with changing vector while iterating it
3702
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3703
0
{
3704
0
    ImGuiContext& g = *ctx;
3705
0
    IM_ASSERT(hook_id != 0);
3706
0
    for (int n = 0; n < g.Hooks.Size; n++)
3707
0
        if (g.Hooks[n].HookId == hook_id)
3708
0
            g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
3709
0
}
3710
3711
// Call context hooks (used by e.g. test engine)
3712
// We assume a small number of hooks so all stored in same array
3713
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3714
128k
{
3715
128k
    ImGuiContext& g = *ctx;
3716
128k
    for (int n = 0; n < g.Hooks.Size; n++)
3717
0
        if (g.Hooks[n].Type == hook_type)
3718
0
            g.Hooks[n].Callback(&g, &g.Hooks[n]);
3719
128k
}
3720
3721
3722
//-----------------------------------------------------------------------------
3723
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3724
//-----------------------------------------------------------------------------
3725
3726
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3727
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3728
4
{
3729
4
    memset(this, 0, sizeof(*this));
3730
4
    Ctx = ctx;
3731
4
    Name = ImStrdup(name);
3732
4
    NameBufLen = (int)strlen(name) + 1;
3733
4
    ID = ImHashStr(name);
3734
4
    IDStack.push_back(ID);
3735
4
    ViewportAllowPlatformMonitorExtend = -1;
3736
4
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3737
4
    MoveId = GetID("#MOVE");
3738
4
    TabId = GetID("#TAB");
3739
4
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3740
4
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3741
4
    AutoFitFramesX = AutoFitFramesY = -1;
3742
4
    AutoPosLastDirection = ImGuiDir_None;
3743
4
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3744
4
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3745
4
    LastFrameActive = -1;
3746
4
    LastFrameJustFocused = -1;
3747
4
    LastTimeActive = -1.0f;
3748
4
    FontWindowScale = FontDpiScale = 1.0f;
3749
4
    SettingsOffset = -1;
3750
4
    DockOrder = -1;
3751
4
    DrawList = &DrawListInst;
3752
4
    DrawList->_Data = &Ctx->DrawListSharedData;
3753
4
    DrawList->_OwnerName = Name;
3754
4
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3755
4
}
3756
3757
ImGuiWindow::~ImGuiWindow()
3758
0
{
3759
0
    IM_ASSERT(DrawList == &DrawListInst);
3760
0
    IM_DELETE(Name);
3761
0
    ColumnsStorage.clear_destruct();
3762
0
}
3763
3764
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3765
59.7k
{
3766
59.7k
    ImGuiID seed = IDStack.back();
3767
59.7k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3768
59.7k
    ImGuiContext& g = *Ctx;
3769
59.7k
    if (g.DebugHookIdInfo == id)
3770
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3771
59.7k
    return id;
3772
59.7k
}
3773
3774
ImGuiID ImGuiWindow::GetID(const void* ptr)
3775
0
{
3776
0
    ImGuiID seed = IDStack.back();
3777
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3778
0
    ImGuiContext& g = *Ctx;
3779
0
    if (g.DebugHookIdInfo == id)
3780
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3781
0
    return id;
3782
0
}
3783
3784
ImGuiID ImGuiWindow::GetID(int n)
3785
4.21k
{
3786
4.21k
    ImGuiID seed = IDStack.back();
3787
4.21k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3788
4.21k
    ImGuiContext& g = *Ctx;
3789
4.21k
    if (g.DebugHookIdInfo == id)
3790
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3791
4.21k
    return id;
3792
4.21k
}
3793
3794
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3795
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3796
0
{
3797
0
    ImGuiID seed = IDStack.back();
3798
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3799
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3800
0
    return id;
3801
0
}
3802
3803
static void SetCurrentWindow(ImGuiWindow* window)
3804
93.9k
{
3805
93.9k
    ImGuiContext& g = *GImGui;
3806
93.9k
    g.CurrentWindow = window;
3807
93.9k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3808
93.9k
    if (window)
3809
72.5k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3810
93.9k
}
3811
3812
void ImGui::GcCompactTransientMiscBuffers()
3813
0
{
3814
0
    ImGuiContext& g = *GImGui;
3815
0
    g.ItemFlagsStack.clear();
3816
0
    g.GroupStack.clear();
3817
0
    TableGcCompactSettings();
3818
0
}
3819
3820
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3821
// Not freed:
3822
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3823
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3824
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3825
2
{
3826
2
    window->MemoryCompacted = true;
3827
2
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3828
2
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3829
2
    window->IDStack.clear();
3830
2
    window->DrawList->_ClearFreeMemory();
3831
2
    window->DC.ChildWindows.clear();
3832
2
    window->DC.ItemWidthStack.clear();
3833
2
    window->DC.TextWrapPosStack.clear();
3834
2
}
3835
3836
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3837
0
{
3838
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3839
    // The other buffers tends to amortize much faster.
3840
0
    window->MemoryCompacted = false;
3841
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3842
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3843
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3844
0
}
3845
3846
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3847
113
{
3848
113
    ImGuiContext& g = *GImGui;
3849
3850
    // Clear previous active id
3851
113
    if (g.ActiveId != 0)
3852
56
    {
3853
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
3854
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3855
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3856
56
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3857
0
        {
3858
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3859
0
            g.MovingWindow = NULL;
3860
0
        }
3861
3862
        // This could be written in a more general way (e.g associate a hook to ActiveId),
3863
        // but since this is currently quite an exception we'll leave it as is.
3864
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3865
56
        if (g.InputTextState.ID == g.ActiveId)
3866
0
            InputTextDeactivateHook(g.ActiveId);
3867
56
    }
3868
3869
    // Set active id
3870
113
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3871
113
    if (g.ActiveIdIsJustActivated)
3872
112
    {
3873
112
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3874
112
        g.ActiveIdTimer = 0.0f;
3875
112
        g.ActiveIdHasBeenPressedBefore = false;
3876
112
        g.ActiveIdHasBeenEditedBefore = false;
3877
112
        g.ActiveIdMouseButton = -1;
3878
112
        if (id != 0)
3879
56
        {
3880
56
            g.LastActiveId = id;
3881
56
            g.LastActiveIdTimer = 0.0f;
3882
56
        }
3883
112
    }
3884
113
    g.ActiveId = id;
3885
113
    g.ActiveIdAllowOverlap = false;
3886
113
    g.ActiveIdNoClearOnFocusLoss = false;
3887
113
    g.ActiveIdWindow = window;
3888
113
    g.ActiveIdHasBeenEditedThisFrame = false;
3889
113
    if (id)
3890
56
    {
3891
56
        g.ActiveIdIsAlive = id;
3892
56
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
3893
56
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
3894
56
    }
3895
3896
    // Clear declaration of inputs claimed by the widget
3897
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3898
113
    g.ActiveIdUsingNavDirMask = 0x00;
3899
113
    g.ActiveIdUsingAllKeyboardKeys = false;
3900
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3901
    g.ActiveIdUsingNavInputMask = 0x00;
3902
#endif
3903
113
}
3904
3905
void ImGui::ClearActiveID()
3906
57
{
3907
57
    SetActiveID(0, NULL); // g.ActiveId = 0;
3908
57
}
3909
3910
void ImGui::SetHoveredID(ImGuiID id)
3911
970
{
3912
970
    ImGuiContext& g = *GImGui;
3913
970
    g.HoveredId = id;
3914
970
    g.HoveredIdAllowOverlap = false;
3915
970
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3916
94
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3917
970
}
3918
3919
ImGuiID ImGui::GetHoveredID()
3920
0
{
3921
0
    ImGuiContext& g = *GImGui;
3922
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3923
0
}
3924
3925
// This is called by ItemAdd().
3926
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
3927
void ImGui::KeepAliveID(ImGuiID id)
3928
55.8k
{
3929
55.8k
    ImGuiContext& g = *GImGui;
3930
55.8k
    if (g.ActiveId == id)
3931
181
        g.ActiveIdIsAlive = id;
3932
55.8k
    if (g.ActiveIdPreviousFrame == id)
3933
193
        g.ActiveIdPreviousFrameIsAlive = true;
3934
55.8k
}
3935
3936
void ImGui::MarkItemEdited(ImGuiID id)
3937
0
{
3938
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
3939
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
3940
0
    ImGuiContext& g = *GImGui;
3941
0
    if (g.ActiveId == id || g.ActiveId == 0)
3942
0
    {
3943
0
        g.ActiveIdHasBeenEditedThisFrame = true;
3944
0
        g.ActiveIdHasBeenEditedBefore = true;
3945
0
    }
3946
3947
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
3948
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
3949
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
3950
3951
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
3952
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
3953
0
}
3954
3955
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
3956
1.06k
{
3957
    // An active popup disable hovering on other windows (apart from its own children)
3958
    // FIXME-OPT: This could be cached/stored within the window.
3959
1.06k
    ImGuiContext& g = *GImGui;
3960
1.06k
    if (g.NavWindow)
3961
308
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
3962
308
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
3963
0
            {
3964
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
3965
                // NB: The 'else' is important because Modal windows are also Popups.
3966
0
                bool want_inhibit = false;
3967
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
3968
0
                    want_inhibit = true;
3969
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
3970
0
                    want_inhibit = true;
3971
3972
                // Inhibit hover unless the window is within the stack of our modal/popup
3973
0
                if (want_inhibit)
3974
0
                    if (!ImGui::IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
3975
0
                        return false;
3976
0
            }
3977
3978
    // Filter by viewport
3979
1.06k
    if (window->Viewport != g.MouseViewport)
3980
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
3981
0
            return false;
3982
3983
1.06k
    return true;
3984
1.06k
}
3985
3986
// This is roughly matching the behavior of internal-facing ItemHoverable()
3987
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
3988
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
3989
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
3990
0
{
3991
0
    ImGuiContext& g = *GImGui;
3992
0
    ImGuiWindow* window = g.CurrentWindow;
3993
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
3994
0
    {
3995
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3996
0
            return false;
3997
0
        if (!IsItemFocused())
3998
0
            return false;
3999
0
    }
4000
0
    else
4001
0
    {
4002
        // Test for bounding box overlap, as updated as ItemAdd()
4003
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4004
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4005
0
            return false;
4006
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4007
4008
        // Done with rectangle culling so we can perform heavier checks now
4009
        // Test if we are hovering the right window (our window could be behind another window)
4010
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4011
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4012
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4013
        // the test that has been running for a long while.
4014
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4015
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
4016
0
                return false;
4017
4018
        // Test if another item is active (e.g. being dragged)
4019
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4020
0
            if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap)
4021
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4022
0
                    return false;
4023
4024
        // Test if interactions on this window are blocked by an active popup or modal.
4025
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4026
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4027
0
            return false;
4028
4029
        // Test if the item is disabled
4030
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4031
0
            return false;
4032
4033
        // Special handling for calling after Begin() which represent the title bar or tab.
4034
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4035
        // will never be overwritten so we need to detect the case.
4036
0
        if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)
4037
0
            return false;
4038
0
    }
4039
4040
    // Handle hover delay
4041
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4042
0
    float delay;
4043
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4044
0
        delay = g.IO.HoverDelayNormal;
4045
0
    else if (flags & ImGuiHoveredFlags_DelayShort)
4046
0
        delay = g.IO.HoverDelayShort;
4047
0
    else
4048
0
        delay = 0.0f;
4049
0
    if (delay > 0.0f)
4050
0
    {
4051
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4052
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverDelayIdPreviousFrame != hover_delay_id))
4053
0
            g.HoverDelayTimer = 0.0f;
4054
0
        g.HoverDelayId = hover_delay_id;
4055
0
        return g.HoverDelayTimer >= delay;
4056
0
    }
4057
4058
0
    return true;
4059
0
}
4060
4061
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4062
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
4063
52.1k
{
4064
52.1k
    ImGuiContext& g = *GImGui;
4065
52.1k
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4066
105
        return false;
4067
4068
52.0k
    ImGuiWindow* window = g.CurrentWindow;
4069
52.0k
    if (g.HoveredWindow != window)
4070
50.6k
        return false;
4071
1.37k
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4072
53
        return false;
4073
1.32k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4074
356
        return false;
4075
4076
    // Done with rectangle culling so we can perform heavier checks now.
4077
970
    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
4078
970
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4079
0
    {
4080
0
        g.HoveredIdDisabled = true;
4081
0
        return false;
4082
0
    }
4083
4084
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4085
    // hover test in widgets code. We could also decide to split this function is two.
4086
970
    if (id != 0)
4087
970
        SetHoveredID(id);
4088
4089
    // When disabled we'll return false but still set HoveredId
4090
970
    if (item_flags & ImGuiItemFlags_Disabled)
4091
0
    {
4092
        // Release active id if turning disabled
4093
0
        if (g.ActiveId == id)
4094
0
            ClearActiveID();
4095
0
        g.HoveredIdDisabled = true;
4096
0
        return false;
4097
0
    }
4098
4099
970
    if (id != 0)
4100
970
    {
4101
        // [DEBUG] Item Picker tool!
4102
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4103
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4104
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4105
970
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4106
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4107
970
        if (g.DebugItemPickerBreakId == id)
4108
0
            IM_DEBUG_BREAK();
4109
970
    }
4110
4111
970
    if (g.NavDisableMouseHover)
4112
21
        return false;
4113
4114
949
    return true;
4115
970
}
4116
4117
// FIXME: This is inlined/duplicated in ItemAdd()
4118
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4119
0
{
4120
0
    ImGuiContext& g = *GImGui;
4121
0
    ImGuiWindow* window = g.CurrentWindow;
4122
0
    if (!bb.Overlaps(window->ClipRect))
4123
0
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4124
0
            if (!g.LogEnabled)
4125
0
                return true;
4126
0
    return false;
4127
0
}
4128
4129
// This is also inlined in ItemAdd()
4130
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4131
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4132
46.9k
{
4133
46.9k
    ImGuiContext& g = *GImGui;
4134
46.9k
    g.LastItemData.ID = item_id;
4135
46.9k
    g.LastItemData.InFlags = in_flags;
4136
46.9k
    g.LastItemData.StatusFlags = item_flags;
4137
46.9k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4138
46.9k
}
4139
4140
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4141
0
{
4142
0
    if (wrap_pos_x < 0.0f)
4143
0
        return 0.0f;
4144
4145
0
    ImGuiContext& g = *GImGui;
4146
0
    ImGuiWindow* window = g.CurrentWindow;
4147
0
    if (wrap_pos_x == 0.0f)
4148
0
    {
4149
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4150
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4151
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4152
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4153
        //else
4154
0
        wrap_pos_x = window->WorkRect.Max.x;
4155
0
    }
4156
0
    else if (wrap_pos_x > 0.0f)
4157
0
    {
4158
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4159
0
    }
4160
4161
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4162
0
}
4163
4164
// IM_ALLOC() == ImGui::MemAlloc()
4165
void* ImGui::MemAlloc(size_t size)
4166
1.22k
{
4167
1.22k
    if (ImGuiContext* ctx = GImGui)
4168
1.22k
        ctx->IO.MetricsActiveAllocations++;
4169
1.22k
    return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4170
1.22k
}
4171
4172
// IM_FREE() == ImGui::MemFree()
4173
void ImGui::MemFree(void* ptr)
4174
1.18k
{
4175
1.18k
    if (ptr)
4176
1.17k
        if (ImGuiContext* ctx = GImGui)
4177
1.17k
            ctx->IO.MetricsActiveAllocations--;
4178
1.18k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4179
1.18k
}
4180
4181
const char* ImGui::GetClipboardText()
4182
0
{
4183
0
    ImGuiContext& g = *GImGui;
4184
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4185
0
}
4186
4187
void ImGui::SetClipboardText(const char* text)
4188
0
{
4189
0
    ImGuiContext& g = *GImGui;
4190
0
    if (g.IO.SetClipboardTextFn)
4191
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4192
0
}
4193
4194
const char* ImGui::GetVersion()
4195
0
{
4196
0
    return IMGUI_VERSION;
4197
0
}
4198
4199
ImGuiIO& ImGui::GetIO()
4200
70.7k
{
4201
70.7k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4202
70.7k
    return GImGui->IO;
4203
70.7k
}
4204
4205
ImGuiPlatformIO& ImGui::GetPlatformIO()
4206
0
{
4207
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4208
0
    return GImGui->PlatformIO;
4209
0
}
4210
4211
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4212
ImDrawData* ImGui::GetDrawData()
4213
21.3k
{
4214
21.3k
    ImGuiContext& g = *GImGui;
4215
21.3k
    ImGuiViewportP* viewport = g.Viewports[0];
4216
21.3k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4217
21.3k
}
4218
4219
double ImGui::GetTime()
4220
70
{
4221
70
    return GImGui->Time;
4222
70
}
4223
4224
int ImGui::GetFrameCount()
4225
0
{
4226
0
    return GImGui->FrameCount;
4227
0
}
4228
4229
static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4230
0
{
4231
    // Create the draw list on demand, because they are not frequently used for all viewports
4232
0
    ImGuiContext& g = *GImGui;
4233
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
4234
0
    ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
4235
0
    if (draw_list == NULL)
4236
0
    {
4237
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4238
0
        draw_list->_OwnerName = drawlist_name;
4239
0
        viewport->DrawLists[drawlist_no] = draw_list;
4240
0
    }
4241
4242
    // Our ImDrawList system requires that there is always a command
4243
0
    if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
4244
0
    {
4245
0
        draw_list->_ResetForNewFrame();
4246
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4247
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4248
0
        viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
4249
0
    }
4250
0
    return draw_list;
4251
0
}
4252
4253
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4254
0
{
4255
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4256
0
}
4257
4258
ImDrawList* ImGui::GetBackgroundDrawList()
4259
0
{
4260
0
    ImGuiContext& g = *GImGui;
4261
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4262
0
}
4263
4264
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4265
0
{
4266
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4267
0
}
4268
4269
ImDrawList* ImGui::GetForegroundDrawList()
4270
0
{
4271
0
    ImGuiContext& g = *GImGui;
4272
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4273
0
}
4274
4275
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4276
0
{
4277
0
    return &GImGui->DrawListSharedData;
4278
0
}
4279
4280
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4281
9
{
4282
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4283
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4284
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4285
9
    ImGuiContext& g = *GImGui;
4286
9
    FocusWindow(window);
4287
9
    SetActiveID(window->MoveId, window);
4288
9
    g.NavDisableHighlight = true;
4289
9
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4290
9
    g.ActiveIdNoClearOnFocusLoss = true;
4291
9
    SetActiveIdUsingAllKeyboardKeys();
4292
4293
9
    bool can_move_window = true;
4294
9
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4295
7
        can_move_window = false;
4296
9
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4297
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4298
0
            can_move_window = false;
4299
9
    if (can_move_window)
4300
2
        g.MovingWindow = window;
4301
9
}
4302
4303
// We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4304
// - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
4305
// - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
4306
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
4307
0
{
4308
0
    ImGuiContext& g = *GImGui;
4309
0
    bool can_undock_node = false;
4310
0
    if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
4311
0
    {
4312
        // Can undock if:
4313
        // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
4314
        // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
4315
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4316
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4317
0
            if (undock_floating_node || root_node->IsDockSpace())
4318
0
                can_undock_node = true;
4319
0
    }
4320
4321
0
    const bool clicked = IsMouseClicked(0);
4322
0
    const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
4323
0
    if (can_undock_node && dragging)
4324
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4325
0
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4326
0
        StartMouseMovingWindow(window);
4327
0
}
4328
4329
// Handle mouse moving window
4330
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4331
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4332
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4333
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4334
void ImGui::UpdateMouseMovingWindowNewFrame()
4335
21.3k
{
4336
21.3k
    ImGuiContext& g = *GImGui;
4337
21.3k
    if (g.MovingWindow != NULL)
4338
4
    {
4339
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4340
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4341
4
        KeepAliveID(g.ActiveId);
4342
4
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4343
4
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4344
4345
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4346
4
        const bool window_disappared = ((!moving_window->WasActive && !moving_window->Active) || moving_window->Viewport == NULL);
4347
4
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4348
2
        {
4349
2
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4350
2
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4351
0
            {
4352
0
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4353
0
                if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4354
0
                {
4355
0
                    moving_window->Viewport->Pos = pos;
4356
0
                    moving_window->Viewport->UpdateWorkRect();
4357
0
                }
4358
0
            }
4359
2
            FocusWindow(g.MovingWindow);
4360
2
        }
4361
2
        else
4362
2
        {
4363
2
            if (!window_disappared)
4364
2
            {
4365
                // Try to merge the window back into the main viewport.
4366
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4367
2
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4368
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4369
4370
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4371
2
                if (!IsDragDropPayloadBeingAccepted())
4372
2
                    g.MouseViewport = moving_window->Viewport;
4373
4374
                // Clear the NoInput window flag set by the Viewport system
4375
2
                moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL.
4376
2
            }
4377
4378
2
            g.MovingWindow = NULL;
4379
2
            ClearActiveID();
4380
2
        }
4381
4
    }
4382
21.3k
    else
4383
21.3k
    {
4384
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4385
21.3k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4386
16
        {
4387
16
            KeepAliveID(g.ActiveId);
4388
16
            if (!g.IO.MouseDown[0])
4389
7
                ClearActiveID();
4390
16
        }
4391
21.3k
    }
4392
21.3k
}
4393
4394
// Initiate moving window when clicking on empty space or title bar.
4395
// Handle left-click and right-click focus.
4396
void ImGui::UpdateMouseMovingWindowEndFrame()
4397
21.3k
{
4398
21.3k
    ImGuiContext& g = *GImGui;
4399
21.3k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4400
989
        return;
4401
4402
    // Unless we just made a window/popup appear
4403
20.3k
    if (g.NavWindow && g.NavWindow->Appearing)
4404
1
        return;
4405
4406
    // Click on empty space to focus window and start moving
4407
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4408
20.3k
    if (g.IO.MouseClicked[0])
4409
398
    {
4410
        // Handle the edge case of a popup being closed while clicking in its empty space.
4411
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4412
398
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4413
398
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4414
4415
398
        if (root_window != NULL && !is_closed_popup)
4416
9
        {
4417
9
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4418
4419
            // Cancel moving if clicked outside of title bar
4420
9
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4421
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4422
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4423
0
                        g.MovingWindow = NULL;
4424
4425
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4426
9
            if (g.HoveredIdDisabled)
4427
0
                g.MovingWindow = NULL;
4428
9
        }
4429
389
        else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
4430
17
        {
4431
            // Clicking on void disable focus
4432
17
            FocusWindow(NULL);
4433
17
        }
4434
398
    }
4435
4436
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4437
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4438
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4439
20.3k
    if (g.IO.MouseClicked[1])
4440
39
    {
4441
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4442
        // This is where we can trim the popup stack.
4443
39
        ImGuiWindow* modal = GetTopMostPopupModal();
4444
39
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4445
39
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4446
39
    }
4447
20.3k
}
4448
4449
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4450
// Need to keep in sync with SetWindowPos()
4451
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4452
0
{
4453
0
    window->Pos += delta;
4454
0
    window->ClipRect.Translate(delta);
4455
0
    window->OuterRectClipped.Translate(delta);
4456
0
    window->InnerRect.Translate(delta);
4457
0
    window->DC.CursorPos += delta;
4458
0
    window->DC.CursorStartPos += delta;
4459
0
    window->DC.CursorMaxPos += delta;
4460
0
    window->DC.IdealMaxPos += delta;
4461
0
}
4462
4463
static void ScaleWindow(ImGuiWindow* window, float scale)
4464
0
{
4465
0
    ImVec2 origin = window->Viewport->Pos;
4466
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4467
0
    window->Size = ImFloor(window->Size * scale);
4468
0
    window->SizeFull = ImFloor(window->SizeFull * scale);
4469
0
    window->ContentSize = ImFloor(window->ContentSize * scale);
4470
0
}
4471
4472
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4473
88.3k
{
4474
88.3k
    return (window->Active) && (!window->Hidden);
4475
88.3k
}
4476
4477
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4478
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4479
21.3k
{
4480
21.3k
    ImGuiContext& g = *GImGui;
4481
21.3k
    ImGuiIO& io = g.IO;
4482
21.3k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4483
4484
    // Find the window hovered by mouse:
4485
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4486
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4487
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4488
21.3k
    bool clear_hovered_windows = false;
4489
21.3k
    FindHoveredWindow();
4490
21.3k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4491
4492
    // Modal windows prevents mouse from hovering behind them.
4493
21.3k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4494
21.3k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4495
0
        clear_hovered_windows = true;
4496
4497
    // Disabled mouse?
4498
21.3k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4499
0
        clear_hovered_windows = true;
4500
4501
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4502
    // won't report hovering nor request capture even while dragging over our windows afterward.
4503
21.3k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4504
21.3k
    const bool has_open_modal = (modal_window != NULL);
4505
21.3k
    int mouse_earliest_down = -1;
4506
21.3k
    bool mouse_any_down = false;
4507
128k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4508
106k
    {
4509
106k
        if (io.MouseClicked[i])
4510
864
        {
4511
864
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4512
864
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4513
864
        }
4514
106k
        mouse_any_down |= io.MouseDown[i];
4515
106k
        if (io.MouseDown[i])
4516
6.58k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4517
5.45k
                mouse_earliest_down = i;
4518
106k
    }
4519
21.3k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4520
21.3k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4521
4522
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4523
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4524
21.3k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4525
21.3k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4526
3.77k
        clear_hovered_windows = true;
4527
4528
21.3k
    if (clear_hovered_windows)
4529
3.77k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4530
4531
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4532
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4533
21.3k
    if (g.WantCaptureMouseNextFrame != -1)
4534
0
    {
4535
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4536
0
    }
4537
21.3k
    else
4538
21.3k
    {
4539
21.3k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4540
21.3k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4541
21.3k
    }
4542
4543
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4544
21.3k
    if (g.WantCaptureKeyboardNextFrame != -1)
4545
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4546
21.3k
    else
4547
21.3k
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4548
21.3k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4549
2.20k
        io.WantCaptureKeyboard = true;
4550
4551
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4552
21.3k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4553
21.3k
}
4554
4555
void ImGui::NewFrame()
4556
21.3k
{
4557
21.3k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4558
21.3k
    ImGuiContext& g = *GImGui;
4559
4560
    // Remove pending delete hooks before frame start.
4561
    // This deferred removal avoid issues of removal while iterating the hook vector
4562
21.3k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4563
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4564
0
            g.Hooks.erase(&g.Hooks[n]);
4565
4566
21.3k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4567
4568
    // Check and assert for various common IO and Configuration mistakes
4569
21.3k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4570
21.3k
    ErrorCheckNewFrameSanityChecks();
4571
21.3k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4572
4573
    // Load settings on first frame, save settings when modified (after a delay)
4574
21.3k
    UpdateSettings();
4575
4576
21.3k
    g.Time += g.IO.DeltaTime;
4577
21.3k
    g.WithinFrameScope = true;
4578
21.3k
    g.FrameCount += 1;
4579
21.3k
    g.TooltipOverrideCount = 0;
4580
21.3k
    g.WindowsActiveCount = 0;
4581
21.3k
    g.MenusIdSubmittedThisFrame.resize(0);
4582
4583
    // Calculate frame-rate for the user, as a purely luxurious feature
4584
21.3k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4585
21.3k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4586
21.3k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4587
21.3k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4588
21.3k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4589
4590
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4591
21.3k
    g.InputEventsTrail.resize(0);
4592
21.3k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4593
4594
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4595
21.3k
    UpdateViewportsNewFrame();
4596
4597
    // Setup current font and draw list shared data
4598
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4599
21.3k
    g.IO.Fonts->Locked = true;
4600
21.3k
    SetCurrentFont(GetDefaultFont());
4601
21.3k
    IM_ASSERT(g.Font->IsLoaded());
4602
21.3k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4603
42.7k
    for (int n = 0; n < g.Viewports.Size; n++)
4604
21.3k
        virtual_space.Add(g.Viewports[n]->GetMainRect());
4605
21.3k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4606
21.3k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4607
21.3k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4608
21.3k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4609
21.3k
    if (g.Style.AntiAliasedLines)
4610
21.3k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4611
21.3k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4612
21.3k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4613
21.3k
    if (g.Style.AntiAliasedFill)
4614
21.3k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4615
21.3k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4616
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4617
4618
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4619
42.7k
    for (int n = 0; n < g.Viewports.Size; n++)
4620
21.3k
    {
4621
21.3k
        ImGuiViewportP* viewport = g.Viewports[n];
4622
21.3k
        viewport->DrawData = NULL;
4623
21.3k
        viewport->DrawDataP.Clear();
4624
21.3k
    }
4625
4626
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4627
21.3k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4628
0
        KeepAliveID(g.DragDropPayload.SourceId);
4629
4630
    // Update HoveredId data
4631
21.3k
    if (!g.HoveredIdPreviousFrame)
4632
20.3k
        g.HoveredIdTimer = 0.0f;
4633
21.3k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4634
20.5k
        g.HoveredIdNotActiveTimer = 0.0f;
4635
21.3k
    if (g.HoveredId)
4636
970
        g.HoveredIdTimer += g.IO.DeltaTime;
4637
21.3k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4638
797
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4639
21.3k
    g.HoveredIdPreviousFrame = g.HoveredId;
4640
21.3k
    g.HoveredId = 0;
4641
21.3k
    g.HoveredIdAllowOverlap = false;
4642
21.3k
    g.HoveredIdDisabled = false;
4643
4644
    // Clear ActiveID if the item is not alive anymore.
4645
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4646
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4647
21.3k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4648
1
    {
4649
1
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4650
1
        ClearActiveID();
4651
1
    }
4652
4653
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4654
21.3k
    if (g.ActiveId)
4655
196
        g.ActiveIdTimer += g.IO.DeltaTime;
4656
21.3k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4657
21.3k
    g.ActiveIdPreviousFrame = g.ActiveId;
4658
21.3k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4659
21.3k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4660
21.3k
    g.ActiveIdIsAlive = 0;
4661
21.3k
    g.ActiveIdHasBeenEditedThisFrame = false;
4662
21.3k
    g.ActiveIdPreviousFrameIsAlive = false;
4663
21.3k
    g.ActiveIdIsJustActivated = false;
4664
21.3k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4665
0
        g.TempInputId = 0;
4666
21.3k
    if (g.ActiveId == 0)
4667
21.1k
    {
4668
21.1k
        g.ActiveIdUsingNavDirMask = 0x00;
4669
21.1k
        g.ActiveIdUsingAllKeyboardKeys = false;
4670
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4671
        g.ActiveIdUsingNavInputMask = 0x00;
4672
#endif
4673
21.1k
    }
4674
4675
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4676
    if (g.ActiveId == 0)
4677
        g.ActiveIdUsingNavInputMask = 0;
4678
    else if (g.ActiveIdUsingNavInputMask != 0)
4679
    {
4680
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4681
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4682
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4683
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4684
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4685
            IM_ASSERT(0); // Other values unsupported
4686
    }
4687
#endif
4688
4689
    // Update hover delay for IsItemHovered() with delays and tooltips
4690
21.3k
    g.HoverDelayIdPreviousFrame = g.HoverDelayId;
4691
21.3k
    if (g.HoverDelayId != 0)
4692
0
    {
4693
        //if (g.IO.MouseDelta.x == 0.0f && g.IO.MouseDelta.y == 0.0f) // Need design/flags
4694
0
        g.HoverDelayTimer += g.IO.DeltaTime;
4695
0
        g.HoverDelayClearTimer = 0.0f;
4696
0
        g.HoverDelayId = 0;
4697
0
    }
4698
21.3k
    else if (g.HoverDelayTimer > 0.0f)
4699
0
    {
4700
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4701
0
        g.HoverDelayClearTimer += g.IO.DeltaTime;
4702
0
        if (g.HoverDelayClearTimer >= ImMax(0.20f, g.IO.DeltaTime * 2.0f)) // ~6 frames at 30 Hz + allow for low framerate
4703
0
            g.HoverDelayTimer = g.HoverDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4704
0
    }
4705
4706
    // Drag and drop
4707
21.3k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4708
21.3k
    g.DragDropAcceptIdCurr = 0;
4709
21.3k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4710
21.3k
    g.DragDropWithinSource = false;
4711
21.3k
    g.DragDropWithinTarget = false;
4712
21.3k
    g.DragDropHoldJustPressedId = 0;
4713
4714
    // Close popups on focus lost (currently wip/opt-in)
4715
    //if (g.IO.AppFocusLost)
4716
    //    ClosePopupsExceptModals();
4717
4718
    // Update keyboard input state
4719
21.3k
    UpdateKeyboardInputs();
4720
4721
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4722
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4723
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4724
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4725
4726
    // Update gamepad/keyboard navigation
4727
21.3k
    NavUpdate();
4728
4729
    // Update mouse input state
4730
21.3k
    UpdateMouseInputs();
4731
4732
    // Undocking
4733
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4734
21.3k
    DockContextNewFrameUpdateUndocking(&g);
4735
4736
    // Find hovered window
4737
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4738
21.3k
    UpdateHoveredWindowAndCaptureFlags();
4739
4740
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4741
21.3k
    UpdateMouseMovingWindowNewFrame();
4742
4743
    // Background darkening/whitening
4744
21.3k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4745
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4746
21.3k
    else
4747
21.3k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4748
4749
21.3k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4750
21.3k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4751
4752
    // Platform IME data: reset for the frame
4753
21.3k
    g.PlatformImeDataPrev = g.PlatformImeData;
4754
21.3k
    g.PlatformImeData.WantVisible = false;
4755
4756
    // Mouse wheel scrolling, scale
4757
21.3k
    UpdateMouseWheel();
4758
4759
    // Mark all windows as not visible and compact unused memory.
4760
21.3k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4761
21.3k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4762
105k
    for (int i = 0; i != g.Windows.Size; i++)
4763
84.1k
    {
4764
84.1k
        ImGuiWindow* window = g.Windows[i];
4765
84.1k
        window->WasActive = window->Active;
4766
84.1k
        window->Active = false;
4767
84.1k
        window->WriteAccessed = false;
4768
84.1k
        window->BeginCountPreviousFrame = window->BeginCount;
4769
84.1k
        window->BeginCount = 0;
4770
4771
        // Garbage collect transient buffers of recently unused windows
4772
84.1k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4773
2
            GcCompactTransientWindowBuffers(window);
4774
84.1k
    }
4775
4776
    // Garbage collect transient buffers of recently unused tables
4777
21.3k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4778
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4779
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4780
21.3k
    for (int i = 0; i < g.TablesTempData.Size; i++)
4781
0
        if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)
4782
0
            TableGcCompactTransientBuffers(&g.TablesTempData[i]);
4783
21.3k
    if (g.GcCompactAll)
4784
0
        GcCompactTransientMiscBuffers();
4785
21.3k
    g.GcCompactAll = false;
4786
4787
    // Closing the focused window restore focus to the first active root window in descending z-order
4788
21.3k
    if (g.NavWindow && !g.NavWindow->WasActive)
4789
0
        FocusTopMostWindowUnderOne(NULL, NULL);
4790
4791
    // No window should be open at the beginning of the frame.
4792
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4793
21.3k
    g.CurrentWindowStack.resize(0);
4794
21.3k
    g.BeginPopupStack.resize(0);
4795
21.3k
    g.ItemFlagsStack.resize(0);
4796
21.3k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4797
21.3k
    g.GroupStack.resize(0);
4798
4799
    // Docking
4800
21.3k
    DockContextNewFrameUpdateDocking(&g);
4801
4802
    // [DEBUG] Update debug features
4803
21.3k
    UpdateDebugToolItemPicker();
4804
21.3k
    UpdateDebugToolStackQueries();
4805
21.3k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4806
0
        g.DebugLocateId = 0;
4807
21.3k
    if (g.DebugLogClipperAutoDisableFrames > 0 && --g.DebugLogClipperAutoDisableFrames == 0)
4808
0
    {
4809
0
        DebugLog("(Auto-disabled ImGuiDebugLogFlags_EventClipper to avoid spamming)\n");
4810
0
        g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
4811
0
    }
4812
4813
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4814
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4815
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4816
21.3k
    g.WithinFrameScopeWithImplicitWindow = true;
4817
21.3k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4818
21.3k
    Begin("Debug##Default");
4819
21.3k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4820
4821
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
4822
    // allowing to validate correct Begin/End behavior in user code.
4823
21.3k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
4824
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
4825
21.3k
    else
4826
21.3k
        g.DebugBeginReturnValueCullDepth = -1;
4827
4828
21.3k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
4829
21.3k
}
4830
4831
// FIXME: Add a more explicit sort order in the window structure.
4832
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
4833
0
{
4834
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
4835
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
4836
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
4837
0
        return d;
4838
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
4839
0
        return d;
4840
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
4841
0
}
4842
4843
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
4844
84.1k
{
4845
84.1k
    out_sorted_windows->push_back(window);
4846
84.1k
    if (window->Active)
4847
25.6k
    {
4848
25.6k
        int count = window->DC.ChildWindows.Size;
4849
25.6k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
4850
29.8k
        for (int i = 0; i < count; i++)
4851
4.22k
        {
4852
4.22k
            ImGuiWindow* child = window->DC.ChildWindows[i];
4853
4.22k
            if (child->Active)
4854
4.22k
                AddWindowToSortBuffer(out_sorted_windows, child);
4855
4.22k
        }
4856
25.6k
    }
4857
84.1k
}
4858
4859
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
4860
25.5k
{
4861
25.5k
    if (draw_list->CmdBuffer.Size == 0)
4862
0
        return;
4863
25.5k
    if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)
4864
14
        return;
4865
4866
    // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
4867
    // May trigger for you if you are using PrimXXX functions incorrectly.
4868
25.5k
    IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
4869
25.5k
    IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
4870
25.5k
    if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
4871
25.5k
        IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
4872
4873
    // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
4874
    // If this assert triggers because you are drawing lots of stuff manually:
4875
    // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
4876
    //   Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
4877
    // - If you want large meshes with more than 64K vertices, you can either:
4878
    //   (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
4879
    //       Most example backends already support this from 1.71. Pre-1.71 backends won't.
4880
    //       Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
4881
    //   (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
4882
    //       Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
4883
    //         glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
4884
    //       Your own engine or render API may use different parameters or function calls to specify index sizes.
4885
    //       2 and 4 bytes indices are generally supported by most graphics API.
4886
    // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
4887
    //   the 64K limit to split your draw commands in multiple draw lists.
4888
25.5k
    if (sizeof(ImDrawIdx) == 2)
4889
25.5k
        IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
4890
4891
25.5k
    out_list->push_back(draw_list);
4892
25.5k
}
4893
4894
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
4895
25.5k
{
4896
25.5k
    ImGuiContext& g = *GImGui;
4897
25.5k
    ImGuiViewportP* viewport = window->Viewport;
4898
25.5k
    g.IO.MetricsRenderWindows++;
4899
25.5k
    if (window->Flags & ImGuiWindowFlags_DockNodeHost)
4900
0
        window->DrawList->ChannelsMerge();
4901
25.5k
    AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
4902
29.8k
    for (int i = 0; i < window->DC.ChildWindows.Size; i++)
4903
4.21k
    {
4904
4.21k
        ImGuiWindow* child = window->DC.ChildWindows[i];
4905
4.21k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
4906
4.21k
            AddWindowToDrawData(child, layer);
4907
4.21k
    }
4908
25.5k
}
4909
4910
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
4911
21.3k
{
4912
21.3k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
4913
21.3k
}
4914
4915
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
4916
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
4917
21.3k
{
4918
21.3k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
4919
21.3k
}
4920
4921
void ImDrawDataBuilder::FlattenIntoSingleLayer()
4922
21.3k
{
4923
21.3k
    int n = Layers[0].Size;
4924
21.3k
    int size = n;
4925
42.7k
    for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
4926
21.3k
        size += Layers[i].Size;
4927
21.3k
    Layers[0].resize(size);
4928
42.7k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
4929
21.3k
    {
4930
21.3k
        ImVector<ImDrawList*>& layer = Layers[layer_n];
4931
21.3k
        if (layer.empty())
4932
21.3k
            continue;
4933
3
        memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
4934
3
        n += layer.Size;
4935
3
        layer.resize(0);
4936
3
    }
4937
21.3k
}
4938
4939
static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
4940
21.3k
{
4941
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
4942
    // and to allow applications/backends to easily skip rendering.
4943
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
4944
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
4945
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
4946
21.3k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_Minimized) != 0;
4947
4948
21.3k
    ImGuiIO& io = ImGui::GetIO();
4949
21.3k
    ImDrawData* draw_data = &viewport->DrawDataP;
4950
21.3k
    viewport->DrawData = draw_data; // Make publicly accessible
4951
21.3k
    draw_data->Valid = true;
4952
21.3k
    draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
4953
21.3k
    draw_data->CmdListsCount = draw_lists->Size;
4954
21.3k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
4955
21.3k
    draw_data->DisplayPos = viewport->Pos;
4956
21.3k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
4957
21.3k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
4958
21.3k
    draw_data->OwnerViewport = viewport;
4959
46.9k
    for (int n = 0; n < draw_lists->Size; n++)
4960
25.5k
    {
4961
25.5k
        ImDrawList* draw_list = draw_lists->Data[n];
4962
25.5k
        draw_list->_PopUnusedDrawCmd();
4963
25.5k
        draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;
4964
25.5k
        draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;
4965
25.5k
    }
4966
21.3k
}
4967
4968
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
4969
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
4970
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
4971
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
4972
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
4973
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
4974
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
4975
93.9k
{
4976
93.9k
    ImGuiWindow* window = GetCurrentWindow();
4977
93.9k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
4978
93.9k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
4979
93.9k
}
4980
4981
void ImGui::PopClipRect()
4982
46.9k
{
4983
46.9k
    ImGuiWindow* window = GetCurrentWindow();
4984
46.9k
    window->DrawList->PopClipRect();
4985
46.9k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
4986
46.9k
}
4987
4988
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
4989
0
{
4990
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
4991
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
4992
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
4993
0
    return window;
4994
0
}
4995
4996
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
4997
0
{
4998
0
    if ((col & IM_COL32_A_MASK) == 0)
4999
0
        return;
5000
5001
0
    ImGuiViewportP* viewport = window->Viewport;
5002
0
    ImRect viewport_rect = viewport->GetMainRect();
5003
5004
    // Draw behind window by moving the draw command at the FRONT of the draw list
5005
0
    {
5006
        // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
5007
        // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5008
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5009
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5010
0
        if (draw_list->CmdBuffer.Size == 0)
5011
0
            draw_list->AddDrawCmd();
5012
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged
5013
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5014
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5015
0
        IM_ASSERT(cmd.ElemCount == 6);
5016
0
        draw_list->CmdBuffer.pop_back();
5017
0
        draw_list->CmdBuffer.push_front(cmd);
5018
0
        draw_list->PopClipRect();
5019
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5020
0
    }
5021
5022
    // Draw over sibling docking nodes in a same docking tree
5023
0
    if (window->RootWindow->DockIsActive)
5024
0
    {
5025
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5026
0
        if (draw_list->CmdBuffer.Size == 0)
5027
0
            draw_list->AddDrawCmd();
5028
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5029
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5030
0
        draw_list->PopClipRect();
5031
0
    }
5032
0
}
5033
5034
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5035
0
{
5036
0
    ImGuiContext& g = *GImGui;
5037
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5038
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5039
0
    {
5040
0
        ImGuiWindow* window = g.Windows[i];
5041
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5042
0
            continue;
5043
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5044
0
            break;
5045
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5046
0
            bottom_most_visible_window = window;
5047
0
    }
5048
0
    return bottom_most_visible_window;
5049
0
}
5050
5051
static void ImGui::RenderDimmedBackgrounds()
5052
21.3k
{
5053
21.3k
    ImGuiContext& g = *GImGui;
5054
21.3k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5055
21.3k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5056
21.3k
        return;
5057
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5058
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5059
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5060
0
        return;
5061
5062
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5063
0
    if (dim_bg_for_modal)
5064
0
    {
5065
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5066
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5067
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5068
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5069
0
    }
5070
0
    else if (dim_bg_for_window_list)
5071
0
    {
5072
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5073
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5074
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5075
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5076
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5077
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5078
5079
        // Draw border around CTRL+Tab target window
5080
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5081
0
        ImGuiViewport* viewport = window->Viewport;
5082
0
        float distance = g.FontSize;
5083
0
        ImRect bb = window->Rect();
5084
0
        bb.Expand(distance);
5085
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5086
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5087
0
        if (window->DrawList->CmdBuffer.Size == 0)
5088
0
            window->DrawList->AddDrawCmd();
5089
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5090
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5091
0
        window->DrawList->PopClipRect();
5092
0
    }
5093
5094
    // Draw dimming background on _other_ viewports than the ones our windows are in
5095
0
    for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
5096
0
    {
5097
0
        ImGuiViewportP* viewport = g.Viewports[viewport_n];
5098
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5099
0
            continue;
5100
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5101
0
            continue;
5102
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5103
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5104
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5105
0
    }
5106
0
}
5107
5108
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5109
void ImGui::EndFrame()
5110
42.7k
{
5111
42.7k
    ImGuiContext& g = *GImGui;
5112
42.7k
    IM_ASSERT(g.Initialized);
5113
5114
    // Don't process EndFrame() multiple times.
5115
42.7k
    if (g.FrameCountEnded == g.FrameCount)
5116
21.3k
        return;
5117
21.3k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5118
5119
21.3k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5120
5121
21.3k
    ErrorCheckEndFrameSanityChecks();
5122
5123
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5124
21.3k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5125
21.3k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5126
0
    {
5127
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5128
0
        IMGUI_DEBUG_LOG_IO("Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5129
0
        if (viewport == NULL)
5130
0
            viewport = GetMainViewport();
5131
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5132
        if (viewport->PlatformHandleRaw == NULL && g.IO.ImeWindowHandle != NULL)
5133
        {
5134
            viewport->PlatformHandleRaw = g.IO.ImeWindowHandle;
5135
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5136
            viewport->PlatformHandleRaw = NULL;
5137
        }
5138
        else
5139
#endif
5140
0
        {
5141
0
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5142
0
        }
5143
0
    }
5144
5145
    // Hide implicit/fallback "Debug" window if it hasn't been used
5146
21.3k
    g.WithinFrameScopeWithImplicitWindow = false;
5147
21.3k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5148
21.3k
        g.CurrentWindow->Active = false;
5149
21.3k
    End();
5150
5151
    // Update navigation: CTRL+Tab, wrap-around requests
5152
21.3k
    NavEndFrame();
5153
5154
    // Update docking
5155
21.3k
    DockContextEndFrame(&g);
5156
5157
21.3k
    SetCurrentViewport(NULL, NULL);
5158
5159
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5160
21.3k
    if (g.DragDropActive)
5161
0
    {
5162
0
        bool is_delivered = g.DragDropPayload.Delivery;
5163
0
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5164
0
        if (is_delivered || is_elapsed)
5165
0
            ClearDragDrop();
5166
0
    }
5167
5168
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5169
21.3k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5170
0
    {
5171
0
        g.DragDropWithinSource = true;
5172
0
        SetTooltip("...");
5173
0
        g.DragDropWithinSource = false;
5174
0
    }
5175
5176
    // End frame
5177
21.3k
    g.WithinFrameScope = false;
5178
21.3k
    g.FrameCountEnded = g.FrameCount;
5179
5180
    // Initiate moving window + handle left-click and right-click focus
5181
21.3k
    UpdateMouseMovingWindowEndFrame();
5182
5183
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5184
21.3k
    UpdateViewportsEndFrame();
5185
5186
    // Sort the window list so that all child windows are after their parent
5187
    // We cannot do that on FocusWindow() because children may not exist yet
5188
21.3k
    g.WindowsTempSortBuffer.resize(0);
5189
21.3k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5190
105k
    for (int i = 0; i != g.Windows.Size; i++)
5191
84.1k
    {
5192
84.1k
        ImGuiWindow* window = g.Windows[i];
5193
84.1k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5194
4.22k
            continue;
5195
79.9k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5196
79.9k
    }
5197
5198
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5199
21.3k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5200
21.3k
    g.Windows.swap(g.WindowsTempSortBuffer);
5201
21.3k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5202
5203
    // Unlock font atlas
5204
21.3k
    g.IO.Fonts->Locked = false;
5205
5206
    // Clear Input data for next frame
5207
21.3k
    g.IO.AppFocusLost = false;
5208
21.3k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5209
21.3k
    g.IO.InputQueueCharacters.resize(0);
5210
5211
21.3k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5212
21.3k
}
5213
5214
// Prepare the data for rendering so you can call GetDrawData()
5215
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5216
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5217
void ImGui::Render()
5218
21.3k
{
5219
21.3k
    ImGuiContext& g = *GImGui;
5220
21.3k
    IM_ASSERT(g.Initialized);
5221
5222
21.3k
    if (g.FrameCountEnded != g.FrameCount)
5223
21.3k
        EndFrame();
5224
21.3k
    const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);
5225
21.3k
    g.FrameCountRendered = g.FrameCount;
5226
21.3k
    g.IO.MetricsRenderWindows = 0;
5227
5228
21.3k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5229
5230
    // Add background ImDrawList (for each active viewport)
5231
42.7k
    for (int n = 0; n != g.Viewports.Size; n++)
5232
21.3k
    {
5233
21.3k
        ImGuiViewportP* viewport = g.Viewports[n];
5234
21.3k
        viewport->DrawDataBuilder.Clear();
5235
21.3k
        if (viewport->DrawLists[0] != NULL)
5236
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5237
21.3k
    }
5238
5239
    // Add ImDrawList to render
5240
21.3k
    ImGuiWindow* windows_to_render_top_most[2];
5241
21.3k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5242
21.3k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5243
105k
    for (int n = 0; n != g.Windows.Size; n++)
5244
84.1k
    {
5245
84.1k
        ImGuiWindow* window = g.Windows[n];
5246
84.1k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5247
84.1k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5248
21.3k
            AddRootWindowToDrawData(window);
5249
84.1k
    }
5250
64.1k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5251
42.7k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5252
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5253
5254
    // Draw modal/window whitening backgrounds
5255
21.3k
    if (first_render_of_frame)
5256
21.3k
        RenderDimmedBackgrounds();
5257
5258
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5259
21.3k
    if (g.IO.MouseDrawCursor && first_render_of_frame && g.MouseCursor != ImGuiMouseCursor_None)
5260
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5261
5262
    // Setup ImDrawData structures for end-user
5263
21.3k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5264
42.7k
    for (int n = 0; n < g.Viewports.Size; n++)
5265
21.3k
    {
5266
21.3k
        ImGuiViewportP* viewport = g.Viewports[n];
5267
21.3k
        viewport->DrawDataBuilder.FlattenIntoSingleLayer();
5268
5269
        // Add foreground ImDrawList (for each active viewport)
5270
21.3k
        if (viewport->DrawLists[1] != NULL)
5271
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5272
5273
21.3k
        SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
5274
21.3k
        ImDrawData* draw_data = viewport->DrawData;
5275
21.3k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5276
21.3k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5277
21.3k
    }
5278
5279
21.3k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5280
21.3k
}
5281
5282
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5283
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5284
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5285
42.7k
{
5286
42.7k
    ImGuiContext& g = *GImGui;
5287
5288
42.7k
    const char* text_display_end;
5289
42.7k
    if (hide_text_after_double_hash)
5290
42.7k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5291
30
    else
5292
30
        text_display_end = text_end;
5293
5294
42.7k
    ImFont* font = g.Font;
5295
42.7k
    const float font_size = g.FontSize;
5296
42.7k
    if (text == text_display_end)
5297
1
        return ImVec2(0.0f, font_size);
5298
42.7k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5299
5300
    // Round
5301
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5302
    // FIXME: Investigate using ceilf or e.g.
5303
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5304
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5305
42.7k
    text_size.x = IM_FLOOR(text_size.x + 0.99999f);
5306
5307
42.7k
    return text_size;
5308
42.7k
}
5309
5310
// Find window given position, search front-to-back
5311
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5312
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5313
// called, aka before the next Begin(). Moving window isn't affected.
5314
static void FindHoveredWindow()
5315
21.3k
{
5316
21.3k
    ImGuiContext& g = *GImGui;
5317
5318
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5319
21.3k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5320
21.3k
    if (g.MovingWindow)
5321
4
        g.MovingWindow->Viewport = g.MouseViewport;
5322
5323
21.3k
    ImGuiWindow* hovered_window = NULL;
5324
21.3k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5325
21.3k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5326
4
        hovered_window = g.MovingWindow;
5327
5328
21.3k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5329
21.3k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5330
102k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5331
81.9k
    {
5332
81.9k
        ImGuiWindow* window = g.Windows[i];
5333
81.9k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5334
81.9k
        if (!window->Active || window->Hidden)
5335
56.4k
            continue;
5336
25.5k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5337
1
            continue;
5338
25.5k
        IM_ASSERT(window->Viewport);
5339
25.5k
        if (window->Viewport != g.MouseViewport)
5340
0
            continue;
5341
5342
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5343
25.5k
        ImRect bb(window->OuterRectClipped);
5344
25.5k
        if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
5345
4.21k
            bb.Expand(padding_regular);
5346
21.3k
        else
5347
21.3k
            bb.Expand(padding_for_resize);
5348
25.5k
        if (!bb.Contains(g.IO.MousePos))
5349
24.4k
            continue;
5350
5351
        // Support for one rectangular hole in any given window
5352
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5353
1.10k
        if (window->HitTestHoleSize.x != 0)
5354
0
        {
5355
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5356
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5357
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5358
0
                continue;
5359
0
        }
5360
5361
1.10k
        if (hovered_window == NULL)
5362
1.10k
            hovered_window = window;
5363
1.10k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5364
1.10k
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5365
1.10k
            hovered_window_ignoring_moving_window = window;
5366
1.10k
        if (hovered_window && hovered_window_ignoring_moving_window)
5367
1.10k
            break;
5368
1.10k
    }
5369
5370
21.3k
    g.HoveredWindow = hovered_window;
5371
21.3k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5372
5373
21.3k
    if (g.MovingWindow)
5374
4
        g.MovingWindow->Viewport = moving_window_viewport;
5375
21.3k
}
5376
5377
bool ImGui::IsItemActive()
5378
42.7k
{
5379
42.7k
    ImGuiContext& g = *GImGui;
5380
42.7k
    if (g.ActiveId)
5381
392
        return g.ActiveId == g.LastItemData.ID;
5382
42.3k
    return false;
5383
42.7k
}
5384
5385
bool ImGui::IsItemActivated()
5386
0
{
5387
0
    ImGuiContext& g = *GImGui;
5388
0
    if (g.ActiveId)
5389
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5390
0
            return true;
5391
0
    return false;
5392
0
}
5393
5394
bool ImGui::IsItemDeactivated()
5395
0
{
5396
0
    ImGuiContext& g = *GImGui;
5397
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5398
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5399
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5400
0
}
5401
5402
bool ImGui::IsItemDeactivatedAfterEdit()
5403
0
{
5404
0
    ImGuiContext& g = *GImGui;
5405
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5406
0
}
5407
5408
// == GetItemID() == GetFocusID()
5409
bool ImGui::IsItemFocused()
5410
0
{
5411
0
    ImGuiContext& g = *GImGui;
5412
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5413
0
        return false;
5414
5415
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5416
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5417
0
    ImGuiWindow* window = g.CurrentWindow;
5418
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5419
0
        return false;
5420
5421
0
    return true;
5422
0
}
5423
5424
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5425
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5426
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5427
0
{
5428
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5429
0
}
5430
5431
bool ImGui::IsItemToggledOpen()
5432
0
{
5433
0
    ImGuiContext& g = *GImGui;
5434
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5435
0
}
5436
5437
bool ImGui::IsItemToggledSelection()
5438
0
{
5439
0
    ImGuiContext& g = *GImGui;
5440
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5441
0
}
5442
5443
bool ImGui::IsAnyItemHovered()
5444
0
{
5445
0
    ImGuiContext& g = *GImGui;
5446
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5447
0
}
5448
5449
bool ImGui::IsAnyItemActive()
5450
0
{
5451
0
    ImGuiContext& g = *GImGui;
5452
0
    return g.ActiveId != 0;
5453
0
}
5454
5455
bool ImGui::IsAnyItemFocused()
5456
0
{
5457
0
    ImGuiContext& g = *GImGui;
5458
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5459
0
}
5460
5461
bool ImGui::IsItemVisible()
5462
0
{
5463
0
    ImGuiContext& g = *GImGui;
5464
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5465
0
}
5466
5467
bool ImGui::IsItemEdited()
5468
0
{
5469
0
    ImGuiContext& g = *GImGui;
5470
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5471
0
}
5472
5473
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5474
// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
5475
void ImGui::SetItemAllowOverlap()
5476
0
{
5477
0
    ImGuiContext& g = *GImGui;
5478
0
    ImGuiID id = g.LastItemData.ID;
5479
0
    if (g.HoveredId == id)
5480
0
        g.HoveredIdAllowOverlap = true;
5481
0
    if (g.ActiveId == id)
5482
0
        g.ActiveIdAllowOverlap = true;
5483
0
}
5484
5485
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5486
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5487
9
{
5488
9
    ImGuiContext& g = *GImGui;
5489
9
    IM_ASSERT(g.ActiveId != 0);
5490
9
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5491
9
    g.ActiveIdUsingAllKeyboardKeys = true;
5492
9
    NavMoveRequestCancel();
5493
9
}
5494
5495
ImGuiID ImGui::GetItemID()
5496
0
{
5497
0
    ImGuiContext& g = *GImGui;
5498
0
    return g.LastItemData.ID;
5499
0
}
5500
5501
ImVec2 ImGui::GetItemRectMin()
5502
0
{
5503
0
    ImGuiContext& g = *GImGui;
5504
0
    return g.LastItemData.Rect.Min;
5505
0
}
5506
5507
ImVec2 ImGui::GetItemRectMax()
5508
0
{
5509
0
    ImGuiContext& g = *GImGui;
5510
0
    return g.LastItemData.Rect.Max;
5511
0
}
5512
5513
ImVec2 ImGui::GetItemRectSize()
5514
0
{
5515
0
    ImGuiContext& g = *GImGui;
5516
0
    return g.LastItemData.Rect.GetSize();
5517
0
}
5518
5519
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
5520
4.22k
{
5521
4.22k
    ImGuiContext& g = *GImGui;
5522
4.22k
    ImGuiWindow* parent_window = g.CurrentWindow;
5523
5524
4.22k
    flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
5525
4.22k
    flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag
5526
5527
    // Size
5528
4.22k
    const ImVec2 content_avail = GetContentRegionAvail();
5529
4.22k
    ImVec2 size = ImFloor(size_arg);
5530
4.22k
    const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
5531
4.22k
    if (size.x <= 0.0f)
5532
3.62k
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
5533
4.22k
    if (size.y <= 0.0f)
5534
3.56k
        size.y = ImMax(content_avail.y + size.y, 4.0f);
5535
4.22k
    SetNextWindowSize(size);
5536
5537
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5538
4.22k
    const char* temp_window_name;
5539
4.22k
    if (name)
5540
4.22k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5541
0
    else
5542
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5543
5544
4.22k
    const float backup_border_size = g.Style.ChildBorderSize;
5545
4.22k
    if (!border)
5546
2.14k
        g.Style.ChildBorderSize = 0.0f;
5547
4.22k
    bool ret = Begin(temp_window_name, NULL, flags);
5548
4.22k
    g.Style.ChildBorderSize = backup_border_size;
5549
5550
4.22k
    ImGuiWindow* child_window = g.CurrentWindow;
5551
4.22k
    child_window->ChildId = id;
5552
4.22k
    child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
5553
5554
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5555
    // While this is not really documented/defined, it seems that the expected thing to do.
5556
4.22k
    if (child_window->BeginCount == 1)
5557
4.22k
        parent_window->DC.CursorPos = child_window->Pos;
5558
5559
    // Process navigation-in immediately so NavInit can run on first frame
5560
4.22k
    if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))
5561
5
    {
5562
5
        FocusWindow(child_window);
5563
5
        NavInitWindow(child_window, false);
5564
5
        SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5565
5
        g.ActiveIdSource = g.NavInputSource;
5566
5
    }
5567
4.22k
    return ret;
5568
4.22k
}
5569
5570
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5571
4.22k
{
5572
4.22k
    ImGuiWindow* window = GetCurrentWindow();
5573
4.22k
    return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
5574
4.22k
}
5575
5576
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5577
0
{
5578
0
    IM_ASSERT(id != 0);
5579
0
    return BeginChildEx(NULL, id, size_arg, border, extra_flags);
5580
0
}
5581
5582
void ImGui::EndChild()
5583
4.22k
{
5584
4.22k
    ImGuiContext& g = *GImGui;
5585
4.22k
    ImGuiWindow* window = g.CurrentWindow;
5586
5587
4.22k
    IM_ASSERT(g.WithinEndChild == false);
5588
4.22k
    IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5589
5590
4.22k
    g.WithinEndChild = true;
5591
4.22k
    if (window->BeginCount > 1)
5592
0
    {
5593
0
        End();
5594
0
    }
5595
4.22k
    else
5596
4.22k
    {
5597
4.22k
        ImVec2 sz = window->Size;
5598
4.22k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
5599
3.62k
            sz.x = ImMax(4.0f, sz.x);
5600
4.22k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
5601
3.56k
            sz.y = ImMax(4.0f, sz.y);
5602
4.22k
        End();
5603
5604
4.22k
        ImGuiWindow* parent_window = g.CurrentWindow;
5605
4.22k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
5606
4.22k
        ItemSize(sz);
5607
4.22k
        if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
5608
3.70k
        {
5609
3.70k
            ItemAdd(bb, window->ChildId);
5610
3.70k
            RenderNavHighlight(bb, window->ChildId);
5611
5612
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5613
3.70k
            if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
5614
2.87k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5615
3.70k
        }
5616
518
        else
5617
518
        {
5618
            // Not navigable into
5619
518
            ItemAdd(bb, 0);
5620
518
        }
5621
4.22k
        if (g.HoveredWindow == window)
5622
63
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5623
4.22k
    }
5624
4.22k
    g.WithinEndChild = false;
5625
4.22k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5626
4.22k
}
5627
5628
// Helper to create a child window / scrolling region that looks like a normal widget frame.
5629
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5630
0
{
5631
0
    ImGuiContext& g = *GImGui;
5632
0
    const ImGuiStyle& style = g.Style;
5633
0
    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5634
0
    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5635
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5636
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5637
0
    bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
5638
0
    PopStyleVar(3);
5639
0
    PopStyleColor();
5640
0
    return ret;
5641
0
}
5642
5643
void ImGui::EndChildFrame()
5644
0
{
5645
0
    EndChild();
5646
0
}
5647
5648
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5649
32
{
5650
32
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5651
32
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5652
32
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5653
32
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5654
32
}
5655
5656
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5657
46.9k
{
5658
46.9k
    ImGuiContext& g = *GImGui;
5659
46.9k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5660
46.9k
}
5661
5662
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5663
46.9k
{
5664
46.9k
    ImGuiID id = ImHashStr(name);
5665
46.9k
    return FindWindowByID(id);
5666
46.9k
}
5667
5668
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5669
0
{
5670
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5671
0
    window->ViewportPos = main_viewport->Pos;
5672
0
    if (settings->ViewportId)
5673
0
    {
5674
0
        window->ViewportId = settings->ViewportId;
5675
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5676
0
    }
5677
0
    window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5678
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5679
0
        window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
5680
0
    window->Collapsed = settings->Collapsed;
5681
0
    window->DockId = settings->DockId;
5682
0
    window->DockOrder = settings->DockOrder;
5683
0
}
5684
5685
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5686
46.9k
{
5687
46.9k
    ImGuiContext& g = *GImGui;
5688
5689
46.9k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5690
46.9k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5691
46.9k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5692
3
    {
5693
3
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5694
3
        g.WindowsFocusOrder.push_back(window);
5695
3
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5696
3
    }
5697
46.9k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5698
0
    {
5699
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5700
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5701
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5702
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5703
0
        window->FocusOrder = -1;
5704
0
    }
5705
46.9k
    window->IsExplicitChild = new_is_explicit_child;
5706
46.9k
}
5707
5708
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5709
4
{
5710
    // Initial window state with e.g. default/arbitrary window position
5711
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5712
4
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5713
4
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5714
4
    window->ViewportPos = main_viewport->Pos;
5715
4
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5716
5717
4
    if (settings != NULL)
5718
0
    {
5719
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5720
0
        ApplyWindowSettings(window, settings);
5721
0
    }
5722
4
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5723
5724
4
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5725
1
    {
5726
1
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5727
1
        window->AutoFitOnlyGrows = false;
5728
1
    }
5729
3
    else
5730
3
    {
5731
3
        if (window->Size.x <= 0.0f)
5732
3
            window->AutoFitFramesX = 2;
5733
3
        if (window->Size.y <= 0.0f)
5734
3
            window->AutoFitFramesY = 2;
5735
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5736
3
    }
5737
4
}
5738
5739
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5740
4
{
5741
    // Create window the first time
5742
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5743
4
    ImGuiContext& g = *GImGui;
5744
4
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5745
4
    window->Flags = flags;
5746
4
    g.WindowsById.SetVoidPtr(window->ID, window);
5747
5748
4
    ImGuiWindowSettings* settings = NULL;
5749
4
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5750
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5751
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5752
5753
4
    InitOrLoadWindowSettings(window, settings);
5754
5755
4
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5756
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5757
4
    else
5758
4
        g.Windows.push_back(window);
5759
5760
4
    return window;
5761
4
}
5762
5763
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5764
0
{
5765
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5766
0
}
5767
5768
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5769
85.4k
{
5770
85.4k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5771
85.4k
}
5772
5773
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5774
93.9k
{
5775
93.9k
    ImGuiContext& g = *GImGui;
5776
93.9k
    ImVec2 new_size = size_desired;
5777
93.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5778
0
    {
5779
        // Using -1,-1 on either X/Y axis to preserve the current size.
5780
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5781
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5782
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5783
0
        if (g.NextWindowData.SizeCallback)
5784
0
        {
5785
0
            ImGuiSizeCallbackData data;
5786
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5787
0
            data.Pos = window->Pos;
5788
0
            data.CurrentSize = window->SizeFull;
5789
0
            data.DesiredSize = new_size;
5790
0
            g.NextWindowData.SizeCallback(&data);
5791
0
            new_size = data.DesiredSize;
5792
0
        }
5793
0
        new_size.x = IM_FLOOR(new_size.x);
5794
0
        new_size.y = IM_FLOOR(new_size.y);
5795
0
    }
5796
5797
    // Minimum size
5798
93.9k
    if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
5799
85.4k
    {
5800
85.4k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5801
85.4k
        new_size = ImMax(new_size, g.Style.WindowMinSize);
5802
85.4k
        const float minimum_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f);
5803
85.4k
        new_size.y = ImMax(new_size.y, minimum_height); // Reduce artifacts with very small windows
5804
85.4k
    }
5805
93.9k
    return new_size;
5806
93.9k
}
5807
5808
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5809
46.9k
{
5810
46.9k
    bool preserve_old_content_sizes = false;
5811
46.9k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5812
17.1k
        preserve_old_content_sizes = true;
5813
29.8k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
5814
0
        preserve_old_content_sizes = true;
5815
46.9k
    if (preserve_old_content_sizes)
5816
17.1k
    {
5817
17.1k
        *content_size_current = window->ContentSize;
5818
17.1k
        *content_size_ideal = window->ContentSizeIdeal;
5819
17.1k
        return;
5820
17.1k
    }
5821
5822
29.8k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
5823
29.8k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
5824
29.8k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
5825
29.8k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
5826
29.8k
}
5827
5828
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
5829
46.9k
{
5830
46.9k
    ImGuiContext& g = *GImGui;
5831
46.9k
    ImGuiStyle& style = g.Style;
5832
46.9k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
5833
46.9k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
5834
46.9k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
5835
46.9k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
5836
46.9k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
5837
15
    {
5838
        // Tooltip always resize
5839
15
        return size_desired;
5840
15
    }
5841
46.9k
    else
5842
46.9k
    {
5843
        // Maximum window size is determined by the viewport size or monitor size
5844
46.9k
        const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
5845
46.9k
        const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
5846
46.9k
        ImVec2 size_min = style.WindowMinSize;
5847
46.9k
        if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5848
0
            size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
5849
5850
46.9k
        ImVec2 avail_size = window->Viewport->WorkSize;
5851
46.9k
        if (window->ViewportOwned)
5852
0
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
5853
46.9k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
5854
46.9k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
5855
0
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
5856
46.9k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
5857
5858
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
5859
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
5860
46.9k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5861
46.9k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
5862
46.9k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
5863
46.9k
        if (will_have_scrollbar_x)
5864
4.22k
            size_auto_fit.y += style.ScrollbarSize;
5865
46.9k
        if (will_have_scrollbar_y)
5866
273
            size_auto_fit.x += style.ScrollbarSize;
5867
46.9k
        return size_auto_fit;
5868
46.9k
    }
5869
46.9k
}
5870
5871
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
5872
0
{
5873
0
    ImVec2 size_contents_current;
5874
0
    ImVec2 size_contents_ideal;
5875
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
5876
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
5877
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5878
0
    return size_final;
5879
0
}
5880
5881
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
5882
29.8k
{
5883
29.8k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
5884
15
        return ImGuiCol_PopupBg;
5885
29.8k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
5886
4.22k
        return ImGuiCol_ChildBg;
5887
25.5k
    return ImGuiCol_WindowBg;
5888
29.8k
}
5889
5890
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
5891
0
{
5892
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
5893
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
5894
0
    ImVec2 size_expected = pos_max - pos_min;
5895
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
5896
0
    *out_pos = pos_min;
5897
0
    if (corner_norm.x == 0.0f)
5898
0
        out_pos->x -= (size_constrained.x - size_expected.x);
5899
0
    if (corner_norm.y == 0.0f)
5900
0
        out_pos->y -= (size_constrained.y - size_expected.y);
5901
0
    *out_size = size_constrained;
5902
0
}
5903
5904
// Data for resizing from corner
5905
struct ImGuiResizeGripDef
5906
{
5907
    ImVec2  CornerPosN;
5908
    ImVec2  InnerDir;
5909
    int     AngleMin12, AngleMax12;
5910
};
5911
static const ImGuiResizeGripDef resize_grip_def[4] =
5912
{
5913
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
5914
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
5915
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
5916
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
5917
};
5918
5919
// Data for resizing from borders
5920
struct ImGuiResizeBorderDef
5921
{
5922
    ImVec2 InnerDir;
5923
    ImVec2 SegmentN1, SegmentN2;
5924
    float  OuterAngle;
5925
};
5926
static const ImGuiResizeBorderDef resize_border_def[4] =
5927
{
5928
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
5929
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
5930
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
5931
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
5932
};
5933
5934
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
5935
0
{
5936
0
    ImRect rect = window->Rect();
5937
0
    if (thickness == 0.0f)
5938
0
        rect.Max -= ImVec2(1, 1);
5939
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
5940
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
5941
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
5942
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
5943
0
    IM_ASSERT(0);
5944
0
    return ImRect();
5945
0
}
5946
5947
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
5948
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
5949
0
{
5950
0
    IM_ASSERT(n >= 0 && n < 4);
5951
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5952
0
    id = ImHashStr("#RESIZE", 0, id);
5953
0
    id = ImHashData(&n, sizeof(int), id);
5954
0
    return id;
5955
0
}
5956
5957
// Borders (Left, Right, Up, Down)
5958
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
5959
0
{
5960
0
    IM_ASSERT(dir >= 0 && dir < 4);
5961
0
    int n = (int)dir + 4;
5962
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5963
0
    id = ImHashStr("#RESIZE", 0, id);
5964
0
    id = ImHashData(&n, sizeof(int), id);
5965
0
    return id;
5966
0
}
5967
5968
// Handle resize for: Resize Grips, Borders, Gamepad
5969
// Return true when using auto-fit (double-click on resize grip)
5970
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
5971
29.8k
{
5972
29.8k
    ImGuiContext& g = *GImGui;
5973
29.8k
    ImGuiWindowFlags flags = window->Flags;
5974
5975
29.8k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
5976
4.23k
        return false;
5977
25.5k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
5978
21.3k
        return false;
5979
5980
4.21k
    bool ret_auto_fit = false;
5981
4.21k
    const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
5982
4.21k
    const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
5983
4.21k
    const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
5984
4.21k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
5985
5986
4.21k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
5987
4.21k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
5988
5989
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
5990
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
5991
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
5992
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
5993
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
5994
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
5995
4.21k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
5996
4.21k
    if (clip_with_viewport_rect)
5997
4.21k
        window->ClipRect = window->Viewport->GetMainRect();
5998
5999
    // Resize grips and borders are on layer 1
6000
4.21k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6001
6002
    // Manual resize grips
6003
4.21k
    PushID("#RESIZE");
6004
8.43k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6005
4.21k
    {
6006
4.21k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6007
4.21k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6008
6009
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6010
4.21k
        bool hovered, held;
6011
4.21k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6012
4.21k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6013
4.21k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6014
4.21k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6015
4.21k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6016
4.21k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6017
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6018
4.21k
        if (hovered || held)
6019
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6020
6021
4.21k
        if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
6022
0
        {
6023
            // Manual auto-fit when double-clicking
6024
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6025
0
            ret_auto_fit = true;
6026
0
            ClearActiveID();
6027
0
        }
6028
4.21k
        else if (held)
6029
0
        {
6030
            // Resize from any of the four corners
6031
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6032
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
6033
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
6034
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6035
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6036
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6037
0
        }
6038
6039
        // Only lower-left grip is visible before hovering/activating
6040
4.21k
        if (resize_grip_n == 0 || held || hovered)
6041
4.21k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6042
4.21k
    }
6043
4.21k
    for (int border_n = 0; border_n < resize_border_count; border_n++)
6044
0
    {
6045
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6046
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6047
6048
0
        bool hovered, held;
6049
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6050
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6051
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6052
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6053
        //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6054
0
        if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
6055
0
        {
6056
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6057
0
            if (held)
6058
0
                *border_held = border_n;
6059
0
        }
6060
0
        if (held)
6061
0
        {
6062
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
6063
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left  ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up   ? visibility_rect.Max.y : +FLT_MAX);
6064
0
            ImVec2 border_target = window->Pos;
6065
0
            border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
6066
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6067
0
            CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6068
0
        }
6069
0
    }
6070
4.21k
    PopID();
6071
6072
    // Restore nav layer
6073
4.21k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6074
6075
    // Navigation resize (keyboard/gamepad)
6076
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6077
    // Not even sure the callback works here.
6078
4.21k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6079
0
    {
6080
0
        ImVec2 nav_resize_dir;
6081
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6082
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6083
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6084
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6085
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6086
0
        {
6087
0
            const float NAV_RESIZE_SPEED = 600.0f;
6088
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6089
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6090
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, visibility_rect.Min - window->Pos - window->Size); // We need Pos+Size >= visibility_rect.Min, so Size >= visibility_rect.Min - Pos, so size_delta >= visibility_rect.Min - window->Pos - window->Size
6091
0
            g.NavWindowingToggleLayer = false;
6092
0
            g.NavDisableMouseHover = true;
6093
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6094
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaSize);
6095
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6096
0
            {
6097
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6098
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6099
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6100
0
            }
6101
0
        }
6102
0
    }
6103
6104
    // Apply back modified position/size to window
6105
4.21k
    if (size_target.x != FLT_MAX)
6106
0
    {
6107
0
        window->SizeFull = size_target;
6108
0
        MarkIniSettingsDirty(window);
6109
0
    }
6110
4.21k
    if (pos_target.x != FLT_MAX)
6111
0
    {
6112
0
        window->Pos = ImFloor(pos_target);
6113
0
        MarkIniSettingsDirty(window);
6114
0
    }
6115
6116
4.21k
    window->Size = window->SizeFull;
6117
4.21k
    return ret_auto_fit;
6118
25.5k
}
6119
6120
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6121
42.7k
{
6122
42.7k
    ImGuiContext& g = *GImGui;
6123
42.7k
    ImVec2 size_for_clamping = window->Size;
6124
42.7k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6125
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6126
42.7k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6127
42.7k
}
6128
6129
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6130
29.8k
{
6131
29.8k
    ImGuiContext& g = *GImGui;
6132
29.8k
    float rounding = window->WindowRounding;
6133
29.8k
    float border_size = window->WindowBorderSize;
6134
29.8k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6135
27.6k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6136
6137
29.8k
    int border_held = window->ResizeBorderHeld;
6138
29.8k
    if (border_held != -1)
6139
0
    {
6140
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_held];
6141
0
        ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
6142
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6143
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6144
0
        window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
6145
0
    }
6146
29.8k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6147
0
    {
6148
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6149
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6150
0
    }
6151
29.8k
}
6152
6153
// Draw background and borders
6154
// Draw and handle scrollbars
6155
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6156
46.9k
{
6157
46.9k
    ImGuiContext& g = *GImGui;
6158
46.9k
    ImGuiStyle& style = g.Style;
6159
46.9k
    ImGuiWindowFlags flags = window->Flags;
6160
6161
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6162
46.9k
    IM_ASSERT(window->BeginCount == 0);
6163
46.9k
    window->SkipItems = false;
6164
6165
    // Draw window + handle manual resize
6166
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6167
46.9k
    const float window_rounding = window->WindowRounding;
6168
46.9k
    const float window_border_size = window->WindowBorderSize;
6169
46.9k
    if (window->Collapsed)
6170
17.1k
    {
6171
        // Title bar only
6172
17.1k
        const float backup_border_size = style.FrameBorderSize;
6173
17.1k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6174
17.1k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6175
17.1k
        if (window->ViewportOwned)
6176
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6177
17.1k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6178
17.1k
        g.Style.FrameBorderSize = backup_border_size;
6179
17.1k
    }
6180
29.8k
    else
6181
29.8k
    {
6182
        // Window background
6183
29.8k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6184
29.8k
        {
6185
29.8k
            bool is_docking_transparent_payload = false;
6186
29.8k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6187
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6188
0
                    is_docking_transparent_payload = true;
6189
6190
29.8k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6191
29.8k
            if (window->ViewportOwned)
6192
0
            {
6193
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6194
0
                if (is_docking_transparent_payload)
6195
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6196
0
            }
6197
29.8k
            else
6198
29.8k
            {
6199
                // Adjust alpha. For docking
6200
29.8k
                bool override_alpha = false;
6201
29.8k
                float alpha = 1.0f;
6202
29.8k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6203
0
                {
6204
0
                    alpha = g.NextWindowData.BgAlphaVal;
6205
0
                    override_alpha = true;
6206
0
                }
6207
29.8k
                if (is_docking_transparent_payload)
6208
0
                {
6209
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6210
0
                    override_alpha = true;
6211
0
                }
6212
29.8k
                if (override_alpha)
6213
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6214
29.8k
            }
6215
6216
            // Render, for docked windows and host windows we ensure bg goes before decorations
6217
29.8k
            if (window->DockIsActive)
6218
0
                window->DockNode->LastBgColor = bg_col;
6219
29.8k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6220
29.8k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6221
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6222
29.8k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6223
29.8k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6224
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6225
29.8k
        }
6226
29.8k
        if (window->DockIsActive)
6227
0
            window->DockNode->IsBgDrawnThisFrame = true;
6228
6229
        // Title bar
6230
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6231
        // in order for their pos/size to be matching their undocking state.)
6232
29.8k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6233
25.5k
        {
6234
25.5k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6235
25.5k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6236
25.5k
        }
6237
6238
        // Menu bar
6239
29.8k
        if (flags & ImGuiWindowFlags_MenuBar)
6240
0
        {
6241
0
            ImRect menu_bar_rect = window->MenuBarRect();
6242
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6243
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6244
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6245
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6246
0
        }
6247
6248
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6249
29.8k
        ImGuiDockNode* node = window->DockNode;
6250
29.8k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6251
0
        {
6252
0
            float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
6253
0
            float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
6254
0
            ImVec2 p = node->Pos;
6255
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6256
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6257
0
            KeepAliveID(unhide_id);
6258
0
            bool hovered, held;
6259
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6260
0
                node->WantHiddenTabBarToggle = true;
6261
0
            else if (held && IsMouseDragging(0))
6262
0
                StartMouseMovingWindowOrNode(window, node, true);
6263
6264
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6265
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6266
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6267
0
        }
6268
6269
        // Scrollbars
6270
29.8k
        if (window->ScrollbarX)
6271
4.22k
            Scrollbar(ImGuiAxis_X);
6272
29.8k
        if (window->ScrollbarY)
6273
4.32k
            Scrollbar(ImGuiAxis_Y);
6274
6275
        // Render resize grips (after their input handling so we don't have a frame of latency)
6276
29.8k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6277
25.5k
        {
6278
51.1k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6279
25.5k
            {
6280
25.5k
                const ImU32 col = resize_grip_col[resize_grip_n];
6281
25.5k
                if ((col & IM_COL32_A_MASK) == 0)
6282
21.3k
                    continue;
6283
4.21k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6284
4.21k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6285
4.21k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6286
4.21k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6287
4.21k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6288
4.21k
                window->DrawList->PathFillConvex(col);
6289
4.21k
            }
6290
25.5k
        }
6291
6292
        // Borders (for dock node host they will be rendered over after the tab bar)
6293
29.8k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6294
29.8k
            RenderWindowOuterBorders(window);
6295
29.8k
    }
6296
46.9k
}
6297
6298
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6299
// Render title text, collapse button, close button
6300
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6301
42.7k
{
6302
42.7k
    ImGuiContext& g = *GImGui;
6303
42.7k
    ImGuiStyle& style = g.Style;
6304
42.7k
    ImGuiWindowFlags flags = window->Flags;
6305
6306
42.7k
    const bool has_close_button = (p_open != NULL);
6307
42.7k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6308
6309
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6310
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6311
42.7k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6312
42.7k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6313
42.7k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6314
6315
    // Layout buttons
6316
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6317
42.7k
    float pad_l = style.FramePadding.x;
6318
42.7k
    float pad_r = style.FramePadding.x;
6319
42.7k
    float button_sz = g.FontSize;
6320
42.7k
    ImVec2 close_button_pos;
6321
42.7k
    ImVec2 collapse_button_pos;
6322
42.7k
    if (has_close_button)
6323
0
    {
6324
0
        pad_r += button_sz;
6325
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6326
0
    }
6327
42.7k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6328
0
    {
6329
0
        pad_r += button_sz;
6330
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6331
0
    }
6332
42.7k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6333
42.7k
    {
6334
42.7k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
6335
42.7k
        pad_l += button_sz;
6336
42.7k
    }
6337
6338
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6339
42.7k
    if (has_collapse_button)
6340
42.7k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6341
0
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6342
6343
    // Close button
6344
42.7k
    if (has_close_button)
6345
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6346
0
            *p_open = false;
6347
6348
42.7k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6349
42.7k
    g.CurrentItemFlags = item_flags_backup;
6350
6351
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6352
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6353
42.7k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6354
42.7k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6355
6356
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6357
    // while uncentered title text will still reach edges correctly.
6358
42.7k
    if (pad_l > style.FramePadding.x)
6359
42.7k
        pad_l += g.Style.ItemInnerSpacing.x;
6360
42.7k
    if (pad_r > style.FramePadding.x)
6361
0
        pad_r += g.Style.ItemInnerSpacing.x;
6362
42.7k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6363
0
    {
6364
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6365
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6366
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6367
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6368
0
    }
6369
6370
42.7k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6371
42.7k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6372
42.7k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6373
0
    {
6374
0
        ImVec2 marker_pos;
6375
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6376
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6377
0
        if (marker_pos.x > layout_r.Min.x)
6378
0
        {
6379
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6380
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6381
0
        }
6382
0
    }
6383
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6384
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6385
42.7k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6386
42.7k
}
6387
6388
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6389
46.9k
{
6390
46.9k
    window->ParentWindow = parent_window;
6391
46.9k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6392
46.9k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6393
4.22k
    {
6394
4.22k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6395
4.22k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6396
4.22k
            window->RootWindow = parent_window->RootWindow;
6397
4.22k
    }
6398
46.9k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6399
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6400
46.9k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6401
4.22k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6402
46.9k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6403
0
    {
6404
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6405
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6406
0
    }
6407
46.9k
}
6408
6409
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6410
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6411
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6412
// - Window             // FindBlockingModal() returns Modal1
6413
//   - Window           //                  .. returns Modal1
6414
//   - Modal1           //                  .. returns Modal2
6415
//      - Window        //                  .. returns Modal2
6416
//          - Window    //                  .. returns Modal2
6417
//          - Modal2    //                  .. returns Modal2
6418
static ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6419
0
{
6420
0
    ImGuiContext& g = *GImGui;
6421
0
    if (g.OpenPopupStack.Size <= 0)
6422
0
        return NULL;
6423
6424
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6425
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
6426
0
    {
6427
0
        ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;
6428
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6429
0
            continue;
6430
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6431
0
            continue;
6432
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window is rendered over last modal, no render order change needed.
6433
0
            break;
6434
0
        for (ImGuiWindow* parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow)
6435
0
            if (IsWindowWithinBeginStackOf(window, parent))
6436
0
                return popup_window;                                // Place window above its begin stack parent.
6437
0
    }
6438
0
    return NULL;
6439
0
}
6440
6441
// Push a new Dear ImGui window to add widgets to.
6442
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6443
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6444
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6445
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6446
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6447
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6448
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6449
46.9k
{
6450
46.9k
    ImGuiContext& g = *GImGui;
6451
46.9k
    const ImGuiStyle& style = g.Style;
6452
46.9k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6453
46.9k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6454
46.9k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6455
6456
    // Find or create
6457
46.9k
    ImGuiWindow* window = FindWindowByName(name);
6458
46.9k
    const bool window_just_created = (window == NULL);
6459
46.9k
    if (window_just_created)
6460
4
        window = CreateNewWindow(name, flags);
6461
6462
    // Automatically disable manual moving/resizing when NoInputs is set
6463
46.9k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6464
15
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6465
6466
46.9k
    if (flags & ImGuiWindowFlags_NavFlattened)
6467
46.9k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6468
6469
46.9k
    const int current_frame = g.FrameCount;
6470
46.9k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6471
46.9k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6472
6473
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6474
46.9k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6475
46.9k
    if (flags & ImGuiWindowFlags_Popup)
6476
0
    {
6477
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6478
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6479
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6480
0
    }
6481
6482
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6483
46.9k
    const bool window_was_appearing = window->Appearing;
6484
46.9k
    if (first_begin_of_the_frame)
6485
46.9k
    {
6486
46.9k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6487
46.9k
        window->Appearing = window_just_activated_by_user;
6488
46.9k
        if (window->Appearing)
6489
16
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6490
46.9k
        window->FlagsPreviousFrame = window->Flags;
6491
46.9k
        window->Flags = (ImGuiWindowFlags)flags;
6492
46.9k
        window->LastFrameActive = current_frame;
6493
46.9k
        window->LastTimeActive = (float)g.Time;
6494
46.9k
        window->BeginOrderWithinParent = 0;
6495
46.9k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6496
46.9k
    }
6497
0
    else
6498
0
    {
6499
0
        flags = window->Flags;
6500
0
    }
6501
6502
    // Docking
6503
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6504
46.9k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6505
46.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6506
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6507
46.9k
    if (first_begin_of_the_frame)
6508
46.9k
    {
6509
46.9k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6510
46.9k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6511
46.9k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6512
46.9k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6513
46.9k
        if (has_dock_node || new_auto_dock_node)
6514
0
        {
6515
0
            BeginDocked(window, p_open);
6516
0
            flags = window->Flags;
6517
0
            if (window->DockIsActive)
6518
0
            {
6519
0
                IM_ASSERT(window->DockNode != NULL);
6520
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6521
0
            }
6522
6523
            // Amend the Appearing flag
6524
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6525
0
            {
6526
0
                window->Appearing = true;
6527
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6528
0
            }
6529
0
        }
6530
46.9k
        else
6531
46.9k
        {
6532
46.9k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6533
46.9k
        }
6534
46.9k
    }
6535
6536
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6537
46.9k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6538
46.9k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6539
46.9k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6540
6541
    // We allow window memory to be compacted so recreate the base stack when needed.
6542
46.9k
    if (window->IDStack.Size == 0)
6543
0
        window->IDStack.push_back(window->ID);
6544
6545
    // Add to stack
6546
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6547
46.9k
    g.CurrentWindow = window;
6548
46.9k
    ImGuiWindowStackData window_stack_data;
6549
46.9k
    window_stack_data.Window = window;
6550
46.9k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6551
46.9k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6552
46.9k
    g.CurrentWindowStack.push_back(window_stack_data);
6553
46.9k
    if (flags & ImGuiWindowFlags_ChildMenu)
6554
0
        g.BeginMenuCount++;
6555
6556
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6557
46.9k
    if (first_begin_of_the_frame)
6558
46.9k
    {
6559
46.9k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6560
46.9k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6561
46.9k
    }
6562
6563
    // Add to focus scope stack
6564
46.9k
    PushFocusScope(window->ID);
6565
46.9k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6566
46.9k
    g.CurrentWindow = NULL;
6567
6568
    // Add to popup stack
6569
46.9k
    if (flags & ImGuiWindowFlags_Popup)
6570
0
    {
6571
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6572
0
        popup_ref.Window = window;
6573
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6574
0
        g.BeginPopupStack.push_back(popup_ref);
6575
0
        window->PopupId = popup_ref.PopupId;
6576
0
    }
6577
6578
    // Process SetNextWindow***() calls
6579
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6580
46.9k
    bool window_pos_set_by_api = false;
6581
46.9k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6582
46.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6583
0
    {
6584
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6585
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6586
0
        {
6587
            // May be processed on the next frame if this is our first frame and we are measuring size
6588
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6589
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6590
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6591
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6592
0
        }
6593
0
        else
6594
0
        {
6595
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6596
0
        }
6597
0
    }
6598
46.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6599
25.5k
    {
6600
25.5k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6601
25.5k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6602
25.5k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6603
25.5k
    }
6604
46.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6605
0
    {
6606
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6607
0
        {
6608
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6609
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6610
0
        }
6611
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6612
0
        {
6613
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6614
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6615
0
        }
6616
0
    }
6617
46.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6618
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6619
46.9k
    else if (first_begin_of_the_frame)
6620
46.9k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6621
46.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6622
0
        window->WindowClass = g.NextWindowData.WindowClass;
6623
46.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6624
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6625
46.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6626
0
        FocusWindow(window);
6627
46.9k
    if (window->Appearing)
6628
16
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6629
6630
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6631
46.9k
    if (first_begin_of_the_frame)
6632
46.9k
    {
6633
        // Initialize
6634
46.9k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6635
46.9k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6636
46.9k
        window->Active = true;
6637
46.9k
        window->HasCloseButton = (p_open != NULL);
6638
46.9k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6639
46.9k
        window->IDStack.resize(1);
6640
46.9k
        window->DrawList->_ResetForNewFrame();
6641
46.9k
        window->DC.CurrentTableIdx = -1;
6642
46.9k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6643
0
        {
6644
0
            window->DrawList->ChannelsSplit(2);
6645
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6646
0
        }
6647
6648
        // Restore buffer capacity when woken from a compacted state, to avoid
6649
46.9k
        if (window->MemoryCompacted)
6650
0
            GcAwakeTransientWindowBuffers(window);
6651
6652
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6653
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6654
46.9k
        bool window_title_visible_elsewhere = false;
6655
46.9k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6656
0
            window_title_visible_elsewhere = true;
6657
46.9k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6658
0
            window_title_visible_elsewhere = true;
6659
46.9k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6660
0
        {
6661
0
            size_t buf_len = (size_t)window->NameBufLen;
6662
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6663
0
            window->NameBufLen = (int)buf_len;
6664
0
        }
6665
6666
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6667
6668
        // Update contents size from last frame for auto-fitting (or use explicit size)
6669
46.9k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6670
6671
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6672
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6673
        // it has a single usage before this code block and may be set below before it is finally checked.
6674
46.9k
        if (window->HiddenFramesCanSkipItems > 0)
6675
0
            window->HiddenFramesCanSkipItems--;
6676
46.9k
        if (window->HiddenFramesCannotSkipItems > 0)
6677
13
            window->HiddenFramesCannotSkipItems--;
6678
46.9k
        if (window->HiddenFramesForRenderOnly > 0)
6679
0
            window->HiddenFramesForRenderOnly--;
6680
6681
        // Hide new windows for one frame until they calculate their size
6682
46.9k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6683
2
            window->HiddenFramesCannotSkipItems = 1;
6684
6685
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6686
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6687
46.9k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6688
12
        {
6689
12
            window->HiddenFramesCannotSkipItems = 1;
6690
12
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6691
12
            {
6692
12
                if (!window_size_x_set_by_api)
6693
12
                    window->Size.x = window->SizeFull.x = 0.f;
6694
12
                if (!window_size_y_set_by_api)
6695
12
                    window->Size.y = window->SizeFull.y = 0.f;
6696
12
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6697
12
            }
6698
12
        }
6699
6700
        // SELECT VIEWPORT
6701
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6702
6703
46.9k
        WindowSelectViewport(window);
6704
46.9k
        SetCurrentViewport(window, window->Viewport);
6705
46.9k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6706
46.9k
        SetCurrentWindow(window);
6707
46.9k
        flags = window->Flags;
6708
6709
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6710
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6711
6712
46.9k
        if (flags & ImGuiWindowFlags_ChildWindow)
6713
4.22k
            window->WindowBorderSize = style.ChildBorderSize;
6714
42.7k
        else
6715
42.7k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6716
46.9k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
6717
2.14k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6718
44.8k
        else
6719
44.8k
            window->WindowPadding = style.WindowPadding;
6720
6721
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6722
46.9k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
6723
46.9k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6724
6725
46.9k
        bool use_current_size_for_scrollbar_x = window_just_created;
6726
46.9k
        bool use_current_size_for_scrollbar_y = window_just_created;
6727
6728
        // Collapse window by double-clicking on title bar
6729
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
6730
46.9k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
6731
42.7k
        {
6732
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
6733
42.7k
            ImRect title_bar_rect = window->TitleBarRect();
6734
42.7k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
6735
3
                window->WantCollapseToggle = true;
6736
42.7k
            if (window->WantCollapseToggle)
6737
3
            {
6738
3
                window->Collapsed = !window->Collapsed;
6739
3
                if (!window->Collapsed)
6740
1
                    use_current_size_for_scrollbar_y = true;
6741
3
                MarkIniSettingsDirty(window);
6742
3
            }
6743
42.7k
        }
6744
4.23k
        else
6745
4.23k
        {
6746
4.23k
            window->Collapsed = false;
6747
4.23k
        }
6748
46.9k
        window->WantCollapseToggle = false;
6749
6750
        // SIZE
6751
6752
        // Outer Decoration Sizes
6753
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
6754
46.9k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
6755
46.9k
        window->DecoOuterSizeX1 = 0.0f;
6756
46.9k
        window->DecoOuterSizeX2 = 0.0f;
6757
46.9k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
6758
46.9k
        window->DecoOuterSizeY2 = 0.0f;
6759
46.9k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
6760
6761
        // Calculate auto-fit size, handle automatic resize
6762
46.9k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
6763
46.9k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6764
15
        {
6765
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6766
15
            if (!window_size_x_set_by_api)
6767
15
            {
6768
15
                window->SizeFull.x = size_auto_fit.x;
6769
15
                use_current_size_for_scrollbar_x = true;
6770
15
            }
6771
15
            if (!window_size_y_set_by_api)
6772
15
            {
6773
15
                window->SizeFull.y = size_auto_fit.y;
6774
15
                use_current_size_for_scrollbar_y = true;
6775
15
            }
6776
15
        }
6777
46.9k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6778
2
        {
6779
            // Auto-fit may only grow window during the first few frames
6780
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6781
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6782
2
            {
6783
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
6784
2
                use_current_size_for_scrollbar_x = true;
6785
2
            }
6786
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6787
2
            {
6788
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
6789
2
                use_current_size_for_scrollbar_y = true;
6790
2
            }
6791
2
            if (!window->Collapsed)
6792
2
                MarkIniSettingsDirty(window);
6793
2
        }
6794
6795
        // Apply minimum/maximum window size constraints and final size
6796
46.9k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
6797
46.9k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
6798
6799
        // POSITION
6800
6801
        // Popup latch its initial position, will position itself when it appears next frame
6802
46.9k
        if (window_just_activated_by_user)
6803
16
        {
6804
16
            window->AutoPosLastDirection = ImGuiDir_None;
6805
16
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
6806
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
6807
16
        }
6808
6809
        // Position child window
6810
46.9k
        if (flags & ImGuiWindowFlags_ChildWindow)
6811
4.22k
        {
6812
4.22k
            IM_ASSERT(parent_window && parent_window->Active);
6813
4.22k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
6814
4.22k
            parent_window->DC.ChildWindows.push_back(window);
6815
4.22k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
6816
4.22k
                window->Pos = parent_window->DC.CursorPos;
6817
4.22k
        }
6818
6819
46.9k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
6820
46.9k
        if (window_pos_with_pivot)
6821
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
6822
46.9k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
6823
0
            window->Pos = FindBestWindowPosForPopup(window);
6824
46.9k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
6825
0
            window->Pos = FindBestWindowPosForPopup(window);
6826
46.9k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
6827
15
            window->Pos = FindBestWindowPosForPopup(window);
6828
6829
        // Late create viewport if we don't fit within our current host viewport.
6830
46.9k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized))
6831
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
6832
0
            {
6833
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
6834
                //ImGuiViewport* old_viewport = window->Viewport;
6835
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
6836
6837
                // FIXME-DPI
6838
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
6839
0
                SetCurrentViewport(window, window->Viewport);
6840
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6841
0
                SetCurrentWindow(window);
6842
0
            }
6843
6844
46.9k
        if (window->ViewportOwned)
6845
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
6846
6847
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
6848
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
6849
46.9k
        ImRect viewport_rect(window->Viewport->GetMainRect());
6850
46.9k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
6851
46.9k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
6852
46.9k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
6853
6854
        // Clamp position/size so window stays visible within its viewport or monitor
6855
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
6856
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
6857
46.9k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
6858
42.7k
        {
6859
42.7k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
6860
42.7k
            {
6861
42.7k
                ClampWindowPos(window, visibility_rect);
6862
42.7k
            }
6863
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
6864
0
            {
6865
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
6866
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
6867
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
6868
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
6869
0
                ClampWindowPos(window, visibility_rect);
6870
0
            }
6871
42.7k
        }
6872
46.9k
        window->Pos = ImFloor(window->Pos);
6873
6874
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
6875
        // Large values tend to lead to variety of artifacts and are not recommended.
6876
46.9k
        if (window->ViewportOwned || window->DockIsActive)
6877
0
            window->WindowRounding = 0.0f;
6878
46.9k
        else
6879
46.9k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
6880
6881
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
6882
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6883
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
6884
6885
        // Apply window focus (new and reactivated windows are moved to front)
6886
46.9k
        bool want_focus = false;
6887
46.9k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
6888
16
        {
6889
16
            if (flags & ImGuiWindowFlags_Popup)
6890
0
                want_focus = true;
6891
16
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
6892
2
                want_focus = true;
6893
6894
16
            ImGuiWindow* modal = GetTopMostPopupModal();
6895
16
            if (modal != NULL && !IsWindowWithinBeginStackOf(window, modal))
6896
0
            {
6897
                // Avoid focusing a window that is created outside of active modal. This will prevent active modal from being closed.
6898
                // Since window is not focused it would reappear at the same display position like the last time it was visible.
6899
                // In case of completely new windows it would go to the top (over current modal), but input to such window would still be blocked by modal.
6900
                // Position window behind a modal that is not a begin-parent of this window.
6901
0
                want_focus = false;
6902
0
                if (window == window->RootWindow)
6903
0
                {
6904
0
                    ImGuiWindow* blocking_modal = FindBlockingModal(window);
6905
0
                    IM_ASSERT(blocking_modal != NULL);
6906
0
                    BringWindowToDisplayBehind(window, blocking_modal);
6907
0
                }
6908
0
            }
6909
16
        }
6910
6911
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
6912
#ifdef IMGUI_ENABLE_TEST_ENGINE
6913
        if (g.TestEngineHookItems)
6914
        {
6915
            IM_ASSERT(window->IDStack.Size == 1);
6916
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
6917
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
6918
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
6919
            window->IDStack.Size = 1;
6920
        }
6921
#endif
6922
6923
        // Decide if we are going to handle borders and resize grips
6924
46.9k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
6925
6926
        // Handle manual resize: Resize Grips, Borders, Gamepad
6927
46.9k
        int border_held = -1;
6928
46.9k
        ImU32 resize_grip_col[4] = {};
6929
46.9k
        const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
6930
46.9k
        const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6931
46.9k
        if (handle_borders_and_resize_grips && !window->Collapsed)
6932
29.8k
            if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
6933
0
                use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
6934
46.9k
        window->ResizeBorderHeld = (signed char)border_held;
6935
6936
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
6937
46.9k
        if (window->ViewportOwned)
6938
0
        {
6939
0
            if (!window->Viewport->PlatformRequestMove)
6940
0
                window->Viewport->Pos = window->Pos;
6941
0
            if (!window->Viewport->PlatformRequestResize)
6942
0
                window->Viewport->Size = window->Size;
6943
0
            window->Viewport->UpdateWorkRect();
6944
0
            viewport_rect = window->Viewport->GetMainRect();
6945
0
        }
6946
6947
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
6948
46.9k
        window->ViewportPos = window->Viewport->Pos;
6949
6950
        // SCROLLBAR VISIBILITY
6951
6952
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
6953
46.9k
        if (!window->Collapsed)
6954
29.8k
        {
6955
            // When reading the current size we need to read it after size constraints have been applied.
6956
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
6957
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
6958
29.8k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
6959
29.8k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
6960
29.8k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
6961
29.8k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
6962
29.8k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
6963
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
6964
29.8k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
6965
29.8k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
6966
29.8k
            if (window->ScrollbarX && !window->ScrollbarY)
6967
524
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
6968
29.8k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
6969
6970
            // Amend the partially filled window->DecorationXXX values.
6971
29.8k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
6972
29.8k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
6973
29.8k
        }
6974
6975
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
6976
        // Update various regions. Variables they depend on should be set above in this function.
6977
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
6978
6979
        // Outer rectangle
6980
        // Not affected by window border size. Used by:
6981
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
6982
        // - Begin() initial clipping rect for drawing window background and borders.
6983
        // - Begin() clipping whole child
6984
46.9k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
6985
46.9k
        const ImRect outer_rect = window->Rect();
6986
46.9k
        const ImRect title_bar_rect = window->TitleBarRect();
6987
46.9k
        window->OuterRectClipped = outer_rect;
6988
46.9k
        if (window->DockIsActive)
6989
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
6990
46.9k
        window->OuterRectClipped.ClipWith(host_rect);
6991
6992
        // Inner rectangle
6993
        // Not affected by window border size. Used by:
6994
        // - InnerClipRect
6995
        // - ScrollToRectEx()
6996
        // - NavUpdatePageUpPageDown()
6997
        // - Scrollbar()
6998
46.9k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
6999
46.9k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7000
46.9k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7001
46.9k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7002
7003
        // Inner clipping rectangle.
7004
        // Will extend a little bit outside the normal work region.
7005
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7006
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7007
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7008
        // Affected by window/frame border size. Used by:
7009
        // - Begin() initial clip rect
7010
46.9k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7011
46.9k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7012
46.9k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7013
46.9k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7014
46.9k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7015
46.9k
        window->InnerClipRect.ClipWithFull(host_rect);
7016
7017
        // Default item width. Make it proportional to window size if window manually resizes
7018
46.9k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7019
46.9k
            window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
7020
15
        else
7021
15
            window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
7022
7023
        // SCROLLING
7024
7025
        // Lock down maximum scrolling
7026
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7027
        // for right/bottom aligned items without creating a scrollbar.
7028
46.9k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7029
46.9k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7030
7031
        // Apply scrolling
7032
46.9k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7033
46.9k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7034
46.9k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7035
7036
        // DRAWING
7037
7038
        // Setup draw list and outer clipping rectangle
7039
46.9k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7040
46.9k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7041
46.9k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7042
7043
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7044
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7045
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7046
46.9k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7047
46.9k
        if (is_undocked_or_docked_visible)
7048
46.9k
        {
7049
46.9k
            bool render_decorations_in_parent = false;
7050
46.9k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7051
4.22k
            {
7052
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7053
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7054
4.22k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7055
4.22k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7056
4.22k
                bool parent_is_empty = parent_window->DrawList->VtxBuffer.Size > 0;
7057
4.22k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_is_empty && !previous_child_overlapping)
7058
4.22k
                    render_decorations_in_parent = true;
7059
4.22k
            }
7060
46.9k
            if (render_decorations_in_parent)
7061
4.22k
                window->DrawList = parent_window->DrawList;
7062
7063
            // Handle title bar, scrollbar, resize grips and resize borders
7064
46.9k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7065
46.9k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7066
46.9k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7067
7068
46.9k
            if (render_decorations_in_parent)
7069
4.22k
                window->DrawList = &window->DrawListInst;
7070
46.9k
        }
7071
7072
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7073
7074
        // Work rectangle.
7075
        // Affected by window padding and border size. Used by:
7076
        // - Columns() for right-most edge
7077
        // - TreeNode(), CollapsingHeader() for right-most edge
7078
        // - BeginTabBar() for right-most edge
7079
46.9k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7080
46.9k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7081
46.9k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7082
46.9k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7083
46.9k
        window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7084
46.9k
        window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7085
46.9k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7086
46.9k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7087
46.9k
        window->ParentWorkRect = window->WorkRect;
7088
7089
        // [LEGACY] Content Region
7090
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7091
        // Used by:
7092
        // - Mouse wheel scrolling + many other things
7093
46.9k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7094
46.9k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7095
46.9k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7096
46.9k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7097
7098
        // Setup drawing context
7099
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7100
46.9k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7101
46.9k
        window->DC.GroupOffset.x = 0.0f;
7102
46.9k
        window->DC.ColumnsOffset.x = 0.0f;
7103
7104
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7105
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7106
46.9k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7107
46.9k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7108
46.9k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7109
46.9k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7110
46.9k
        window->DC.CursorPos = window->DC.CursorStartPos;
7111
46.9k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7112
46.9k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7113
46.9k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7114
46.9k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7115
46.9k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7116
46.9k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7117
7118
46.9k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7119
46.9k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7120
46.9k
        window->DC.NavLayersActiveMaskNext = 0x00;
7121
46.9k
        window->DC.NavHideHighlightOneFrame = false;
7122
46.9k
        window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
7123
7124
46.9k
        window->DC.MenuBarAppending = false;
7125
46.9k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7126
46.9k
        window->DC.TreeDepth = 0;
7127
46.9k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7128
46.9k
        window->DC.ChildWindows.resize(0);
7129
46.9k
        window->DC.StateStorage = &window->StateStorage;
7130
46.9k
        window->DC.CurrentColumns = NULL;
7131
46.9k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7132
46.9k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7133
7134
46.9k
        window->DC.ItemWidth = window->ItemWidthDefault;
7135
46.9k
        window->DC.TextWrapPos = -1.0f; // disabled
7136
46.9k
        window->DC.ItemWidthStack.resize(0);
7137
46.9k
        window->DC.TextWrapPosStack.resize(0);
7138
7139
46.9k
        if (window->AutoFitFramesX > 0)
7140
4
            window->AutoFitFramesX--;
7141
46.9k
        if (window->AutoFitFramesY > 0)
7142
4
            window->AutoFitFramesY--;
7143
7144
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7145
46.9k
        if (want_focus)
7146
2
        {
7147
2
            FocusWindow(window);
7148
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7149
2
        }
7150
7151
        // Close requested by platform window
7152
46.9k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7153
0
        {
7154
0
            if (!window->DockIsActive || window->DockTabIsVisible)
7155
0
            {
7156
0
                window->Viewport->PlatformRequestClose = false;
7157
0
                g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
7158
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' PlatformRequestClose\n", window->Name);
7159
0
                *p_open = false;
7160
0
            }
7161
0
        }
7162
7163
        // Title bar
7164
46.9k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7165
42.7k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7166
7167
        // Clear hit test shape every frame
7168
46.9k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7169
7170
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7171
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7172
        // Maybe we can support CTRL+C on every element?
7173
        /*
7174
        //if (g.NavWindow == window && g.ActiveId == 0)
7175
        if (g.ActiveId == window->MoveId)
7176
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7177
                LogToClipboard();
7178
        */
7179
7180
46.9k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7181
46.9k
        {
7182
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7183
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7184
46.9k
            if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift))
7185
2
                if ((window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7186
2
                    BeginDockableDragDropSource(window);
7187
7188
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7189
46.9k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7190
0
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7191
0
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7192
0
                        BeginDockableDragDropTarget(window);
7193
46.9k
        }
7194
7195
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7196
        // This is useful to allow creating context menus on title bar only, etc.
7197
46.9k
        if (window->DockIsActive)
7198
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7199
46.9k
        else
7200
46.9k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7201
7202
        // [DEBUG]
7203
46.9k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7204
46.9k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7205
0
            DebugLocateItemResolveWithLastItem();
7206
46.9k
#endif
7207
7208
        // [Test Engine] Register title bar / tab with MoveId.
7209
#ifdef IMGUI_ENABLE_TEST_ENGINE
7210
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7211
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7212
#endif
7213
46.9k
    }
7214
0
    else
7215
0
    {
7216
        // Append
7217
0
        SetCurrentViewport(window, window->Viewport);
7218
0
        SetCurrentWindow(window);
7219
0
    }
7220
7221
46.9k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7222
46.9k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7223
7224
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7225
46.9k
    window->WriteAccessed = false;
7226
46.9k
    window->BeginCount++;
7227
46.9k
    g.NextWindowData.ClearFlags();
7228
7229
    // Update visibility
7230
46.9k
    if (first_begin_of_the_frame)
7231
46.9k
    {
7232
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7233
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7234
        // This is analogous to regular windows being hidden from one frame.
7235
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7236
46.9k
        if (window->DockIsActive && !window->DockTabIsVisible)
7237
0
        {
7238
0
            if (window->LastFrameJustFocused == g.FrameCount)
7239
0
                window->HiddenFramesCannotSkipItems = 1;
7240
0
            else
7241
0
                window->HiddenFramesCanSkipItems = 1;
7242
0
        }
7243
7244
46.9k
        if (flags & ImGuiWindowFlags_ChildWindow)
7245
4.22k
        {
7246
            // Child window can be out of sight and have "negative" clip windows.
7247
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7248
4.22k
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
7249
4.22k
            if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
7250
4.22k
            {
7251
4.22k
                const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7252
4.22k
                if (!g.LogEnabled && !nav_request)
7253
4.22k
                    if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7254
0
                        window->HiddenFramesCanSkipItems = 1;
7255
4.22k
            }
7256
7257
            // Hide along with parent or if parent is collapsed
7258
4.22k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7259
0
                window->HiddenFramesCanSkipItems = 1;
7260
4.22k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7261
1
                window->HiddenFramesCannotSkipItems = 1;
7262
4.22k
        }
7263
7264
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7265
46.9k
        if (style.Alpha <= 0.0f)
7266
0
            window->HiddenFramesCanSkipItems = 1;
7267
7268
        // Update the Hidden flag
7269
46.9k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7270
46.9k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7271
7272
        // Disable inputs for requested number of frames
7273
46.9k
        if (window->DisableInputsFrames > 0)
7274
0
        {
7275
0
            window->DisableInputsFrames--;
7276
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7277
0
        }
7278
7279
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7280
46.9k
        bool skip_items = false;
7281
46.9k
        if (window->Collapsed || !window->Active || hidden_regular)
7282
17.1k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7283
17.1k
                skip_items = true;
7284
46.9k
        window->SkipItems = skip_items;
7285
7286
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7287
46.9k
        if (window->SkipItems)
7288
17.1k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7289
7290
        // Sanity check: there are two spots which can set Appearing = true
7291
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7292
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7293
46.9k
        if (window->SkipItems && !window->Appearing)
7294
46.9k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7295
46.9k
    }
7296
7297
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7298
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7299
46.9k
    if (!window->IsFallbackWindow && ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size)))
7300
0
    {
7301
0
        if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7302
0
        if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7303
0
        return false;
7304
0
    }
7305
7306
46.9k
    return !window->SkipItems;
7307
46.9k
}
7308
7309
void ImGui::End()
7310
46.9k
{
7311
46.9k
    ImGuiContext& g = *GImGui;
7312
46.9k
    ImGuiWindow* window = g.CurrentWindow;
7313
7314
    // Error checking: verify that user hasn't called End() too many times!
7315
46.9k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7316
0
    {
7317
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7318
0
        return;
7319
0
    }
7320
46.9k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7321
7322
    // Error checking: verify that user doesn't directly call End() on a child window.
7323
46.9k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7324
46.9k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7325
7326
    // Close anything that is open
7327
46.9k
    if (window->DC.CurrentColumns)
7328
0
        EndColumns();
7329
46.9k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7330
46.9k
        PopClipRect();
7331
46.9k
    PopFocusScope();
7332
7333
    // Stop logging
7334
46.9k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7335
42.7k
        LogFinish();
7336
7337
46.9k
    if (window->DC.IsSetPos)
7338
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7339
7340
    // Docking: report contents sizes to parent to allow for auto-resize
7341
46.9k
    if (window->DockNode && window->DockTabIsVisible)
7342
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7343
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7344
7345
    // Pop from window stack
7346
46.9k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7347
46.9k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7348
0
        g.BeginMenuCount--;
7349
46.9k
    if (window->Flags & ImGuiWindowFlags_Popup)
7350
0
        g.BeginPopupStack.pop_back();
7351
46.9k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7352
46.9k
    g.CurrentWindowStack.pop_back();
7353
46.9k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7354
46.9k
    if (g.CurrentWindow)
7355
25.6k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7356
46.9k
}
7357
7358
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7359
2.66k
{
7360
2.66k
    ImGuiContext& g = *GImGui;
7361
2.66k
    IM_ASSERT(window == window->RootWindow);
7362
7363
2.66k
    const int cur_order = window->FocusOrder;
7364
2.66k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7365
2.66k
    if (g.WindowsFocusOrder.back() == window)
7366
2.66k
        return;
7367
7368
1
    const int new_order = g.WindowsFocusOrder.Size - 1;
7369
2
    for (int n = cur_order; n < new_order; n++)
7370
1
    {
7371
1
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7372
1
        g.WindowsFocusOrder[n]->FocusOrder--;
7373
1
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7374
1
    }
7375
1
    g.WindowsFocusOrder[new_order] = window;
7376
1
    window->FocusOrder = (short)new_order;
7377
1
}
7378
7379
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7380
2.66k
{
7381
2.66k
    ImGuiContext& g = *GImGui;
7382
2.66k
    ImGuiWindow* current_front_window = g.Windows.back();
7383
2.66k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7384
2.66k
        return;
7385
2
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7386
2
        if (g.Windows[i] == window)
7387
1
        {
7388
1
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7389
1
            g.Windows[g.Windows.Size - 1] = window;
7390
1
            break;
7391
1
        }
7392
1
}
7393
7394
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7395
0
{
7396
0
    ImGuiContext& g = *GImGui;
7397
0
    if (g.Windows[0] == window)
7398
0
        return;
7399
0
    for (int i = 0; i < g.Windows.Size; i++)
7400
0
        if (g.Windows[i] == window)
7401
0
        {
7402
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7403
0
            g.Windows[0] = window;
7404
0
            break;
7405
0
        }
7406
0
}
7407
7408
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7409
0
{
7410
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7411
0
    ImGuiContext& g = *GImGui;
7412
0
    window = window->RootWindow;
7413
0
    behind_window = behind_window->RootWindow;
7414
0
    int pos_wnd = FindWindowDisplayIndex(window);
7415
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7416
0
    if (pos_wnd < pos_beh)
7417
0
    {
7418
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7419
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7420
0
        g.Windows[pos_beh - 1] = window;
7421
0
    }
7422
0
    else
7423
0
    {
7424
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7425
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7426
0
        g.Windows[pos_beh] = window;
7427
0
    }
7428
0
}
7429
7430
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7431
0
{
7432
0
    ImGuiContext& g = *GImGui;
7433
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7434
0
}
7435
7436
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7437
void ImGui::FocusWindow(ImGuiWindow* window)
7438
7.80k
{
7439
7.80k
    ImGuiContext& g = *GImGui;
7440
7441
7.80k
    if (g.NavWindow != window)
7442
2.43k
    {
7443
2.43k
        SetNavWindow(window);
7444
2.43k
        if (window && g.NavDisableMouseHover)
7445
162
            g.NavMousePosDirty = true;
7446
2.43k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7447
2.43k
        g.NavLayer = ImGuiNavLayer_Main;
7448
2.43k
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7449
2.43k
        g.NavIdIsAlive = false;
7450
7451
        // Close popups if any
7452
2.43k
        ClosePopupsOverWindow(window, false);
7453
2.43k
    }
7454
7455
    // Move the root window to the top of the pile
7456
7.80k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7457
7.80k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7458
7.80k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7459
7.80k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7460
7.80k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7461
7462
    // Steal active widgets. Some of the cases it triggers includes:
7463
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7464
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7465
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7466
7.80k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7467
45
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7468
34
            ClearActiveID();
7469
7470
    // Passing NULL allow to disable keyboard focus
7471
7.80k
    if (!window)
7472
5.14k
        return;
7473
2.66k
    window->LastFrameJustFocused = g.FrameCount;
7474
7475
    // Select in dock node
7476
2.66k
    if (dock_node && dock_node->TabBar)
7477
0
        dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7478
7479
    // Bring to front
7480
2.66k
    BringWindowToFocusFront(focus_front_window);
7481
2.66k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7482
2.66k
        BringWindowToDisplayFront(display_front_window);
7483
2.66k
}
7484
7485
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
7486
0
{
7487
0
    ImGuiContext& g = *GImGui;
7488
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7489
0
    if (under_this_window != NULL)
7490
0
    {
7491
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7492
0
        int offset = -1;
7493
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7494
0
        {
7495
0
            under_this_window = under_this_window->ParentWindow;
7496
0
            offset = 0;
7497
0
        }
7498
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7499
0
    }
7500
0
    for (int i = start_idx; i >= 0; i--)
7501
0
    {
7502
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7503
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7504
0
        IM_ASSERT(window == window->RootWindow);
7505
0
        if (window != ignore_window && window->WasActive)
7506
0
            if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7507
0
            {
7508
                // FIXME-DOCK: This is failing (lagging by one frame) for docked windows.
7509
                // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7510
                // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7511
                // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7512
0
                ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
7513
0
                FocusWindow(focus_window);
7514
0
                return;
7515
0
            }
7516
0
    }
7517
0
    FocusWindow(NULL);
7518
0
}
7519
7520
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7521
void ImGui::SetCurrentFont(ImFont* font)
7522
21.3k
{
7523
21.3k
    ImGuiContext& g = *GImGui;
7524
21.3k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7525
21.3k
    IM_ASSERT(font->Scale > 0.0f);
7526
21.3k
    g.Font = font;
7527
21.3k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7528
21.3k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7529
7530
21.3k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7531
21.3k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7532
21.3k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7533
21.3k
    g.DrawListSharedData.Font = g.Font;
7534
21.3k
    g.DrawListSharedData.FontSize = g.FontSize;
7535
21.3k
}
7536
7537
void ImGui::PushFont(ImFont* font)
7538
0
{
7539
0
    ImGuiContext& g = *GImGui;
7540
0
    if (!font)
7541
0
        font = GetDefaultFont();
7542
0
    SetCurrentFont(font);
7543
0
    g.FontStack.push_back(font);
7544
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7545
0
}
7546
7547
void  ImGui::PopFont()
7548
0
{
7549
0
    ImGuiContext& g = *GImGui;
7550
0
    g.CurrentWindow->DrawList->PopTextureID();
7551
0
    g.FontStack.pop_back();
7552
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7553
0
}
7554
7555
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7556
4.22k
{
7557
4.22k
    ImGuiContext& g = *GImGui;
7558
4.22k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7559
4.22k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7560
4.22k
    if (enabled)
7561
0
        item_flags |= option;
7562
4.22k
    else
7563
4.22k
        item_flags &= ~option;
7564
4.22k
    g.CurrentItemFlags = item_flags;
7565
4.22k
    g.ItemFlagsStack.push_back(item_flags);
7566
4.22k
}
7567
7568
void ImGui::PopItemFlag()
7569
4.22k
{
7570
4.22k
    ImGuiContext& g = *GImGui;
7571
4.22k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7572
4.22k
    g.ItemFlagsStack.pop_back();
7573
4.22k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7574
4.22k
}
7575
7576
// BeginDisabled()/EndDisabled()
7577
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7578
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7579
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7580
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7581
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7582
void ImGui::BeginDisabled(bool disabled)
7583
0
{
7584
0
    ImGuiContext& g = *GImGui;
7585
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7586
0
    if (!was_disabled && disabled)
7587
0
    {
7588
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7589
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7590
0
    }
7591
0
    if (was_disabled || disabled)
7592
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7593
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7594
0
    g.DisabledStackSize++;
7595
0
}
7596
7597
void ImGui::EndDisabled()
7598
0
{
7599
0
    ImGuiContext& g = *GImGui;
7600
0
    IM_ASSERT(g.DisabledStackSize > 0);
7601
0
    g.DisabledStackSize--;
7602
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7603
    //PopItemFlag();
7604
0
    g.ItemFlagsStack.pop_back();
7605
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7606
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7607
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7608
0
}
7609
7610
void ImGui::PushTabStop(bool tab_stop)
7611
4.22k
{
7612
4.22k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7613
4.22k
}
7614
7615
void ImGui::PopTabStop()
7616
4.22k
{
7617
4.22k
    PopItemFlag();
7618
4.22k
}
7619
7620
void ImGui::PushButtonRepeat(bool repeat)
7621
0
{
7622
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7623
0
}
7624
7625
void ImGui::PopButtonRepeat()
7626
0
{
7627
0
    PopItemFlag();
7628
0
}
7629
7630
void ImGui::PushTextWrapPos(float wrap_pos_x)
7631
0
{
7632
0
    ImGuiWindow* window = GetCurrentWindow();
7633
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7634
0
    window->DC.TextWrapPos = wrap_pos_x;
7635
0
}
7636
7637
void ImGui::PopTextWrapPos()
7638
0
{
7639
0
    ImGuiWindow* window = GetCurrentWindow();
7640
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7641
0
    window->DC.TextWrapPosStack.pop_back();
7642
0
}
7643
7644
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7645
0
{
7646
0
    ImGuiWindow* last_window = NULL;
7647
0
    while (last_window != window)
7648
0
    {
7649
0
        last_window = window;
7650
0
        window = window->RootWindow;
7651
0
        if (popup_hierarchy)
7652
0
            window = window->RootWindowPopupTree;
7653
0
    if (dock_hierarchy)
7654
0
      window = window->RootWindowDockTree;
7655
0
  }
7656
0
    return window;
7657
0
}
7658
7659
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7660
0
{
7661
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7662
0
    if (window_root == potential_parent)
7663
0
        return true;
7664
0
    while (window != NULL)
7665
0
    {
7666
0
        if (window == potential_parent)
7667
0
            return true;
7668
0
        if (window == window_root) // end of chain
7669
0
            return false;
7670
0
        window = window->ParentWindow;
7671
0
    }
7672
0
    return false;
7673
0
}
7674
7675
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7676
0
{
7677
0
    if (window->RootWindow == potential_parent)
7678
0
        return true;
7679
0
    while (window != NULL)
7680
0
    {
7681
0
        if (window == potential_parent)
7682
0
            return true;
7683
0
        window = window->ParentWindowInBeginStack;
7684
0
    }
7685
0
    return false;
7686
0
}
7687
7688
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7689
0
{
7690
0
    ImGuiContext& g = *GImGui;
7691
7692
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7693
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7694
0
    if (display_layer_delta != 0)
7695
0
        return display_layer_delta > 0;
7696
7697
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7698
0
    {
7699
0
        ImGuiWindow* candidate_window = g.Windows[i];
7700
0
        if (candidate_window == potential_above)
7701
0
            return true;
7702
0
        if (candidate_window == potential_below)
7703
0
            return false;
7704
0
    }
7705
0
    return false;
7706
0
}
7707
7708
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7709
6.14k
{
7710
6.14k
    IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0);   // Flags not supported by this function
7711
6.14k
    ImGuiContext& g = *GImGui;
7712
6.14k
    ImGuiWindow* ref_window = g.HoveredWindow;
7713
6.14k
    ImGuiWindow* cur_window = g.CurrentWindow;
7714
6.14k
    if (ref_window == NULL)
7715
5.81k
        return false;
7716
7717
323
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
7718
323
    {
7719
323
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
7720
323
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
7721
323
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
7722
323
        if (flags & ImGuiHoveredFlags_RootWindow)
7723
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7724
7725
323
        bool result;
7726
323
        if (flags & ImGuiHoveredFlags_ChildWindows)
7727
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7728
323
        else
7729
323
            result = (ref_window == cur_window);
7730
323
        if (!result)
7731
233
            return false;
7732
323
    }
7733
7734
90
    if (!IsWindowContentHoverable(ref_window, flags))
7735
0
        return false;
7736
90
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
7737
90
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
7738
0
            return false;
7739
90
    return true;
7740
90
}
7741
7742
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
7743
8.38k
{
7744
8.38k
    ImGuiContext& g = *GImGui;
7745
8.38k
    ImGuiWindow* ref_window = g.NavWindow;
7746
8.38k
    ImGuiWindow* cur_window = g.CurrentWindow;
7747
7748
8.38k
    if (ref_window == NULL)
7749
4.42k
        return false;
7750
3.96k
    if (flags & ImGuiFocusedFlags_AnyWindow)
7751
0
        return true;
7752
7753
3.96k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
7754
3.96k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
7755
3.96k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
7756
3.96k
    if (flags & ImGuiHoveredFlags_RootWindow)
7757
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7758
7759
3.96k
    if (flags & ImGuiHoveredFlags_ChildWindows)
7760
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7761
3.96k
    else
7762
3.96k
        return (ref_window == cur_window);
7763
3.96k
}
7764
7765
ImGuiID ImGui::GetWindowDockID()
7766
0
{
7767
0
    ImGuiContext& g = *GImGui;
7768
0
    return g.CurrentWindow->DockId;
7769
0
}
7770
7771
bool ImGui::IsWindowDocked()
7772
0
{
7773
0
    ImGuiContext& g = *GImGui;
7774
0
    return g.CurrentWindow->DockIsActive;
7775
0
}
7776
7777
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
7778
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
7779
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
7780
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
7781
0
{
7782
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
7783
0
}
7784
7785
float ImGui::GetWindowWidth()
7786
2.57k
{
7787
2.57k
    ImGuiWindow* window = GImGui->CurrentWindow;
7788
2.57k
    return window->Size.x;
7789
2.57k
}
7790
7791
float ImGui::GetWindowHeight()
7792
2.58k
{
7793
2.58k
    ImGuiWindow* window = GImGui->CurrentWindow;
7794
2.58k
    return window->Size.y;
7795
2.58k
}
7796
7797
ImVec2 ImGui::GetWindowPos()
7798
0
{
7799
0
    ImGuiContext& g = *GImGui;
7800
0
    ImGuiWindow* window = g.CurrentWindow;
7801
0
    return window->Pos;
7802
0
}
7803
7804
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
7805
0
{
7806
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7807
0
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
7808
0
        return;
7809
7810
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7811
0
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7812
0
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
7813
7814
    // Set
7815
0
    const ImVec2 old_pos = window->Pos;
7816
0
    window->Pos = ImFloor(pos);
7817
0
    ImVec2 offset = window->Pos - old_pos;
7818
0
    if (offset.x == 0.0f && offset.y == 0.0f)
7819
0
        return;
7820
0
    MarkIniSettingsDirty(window);
7821
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
7822
0
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
7823
0
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
7824
0
    window->DC.IdealMaxPos += offset;
7825
0
    window->DC.CursorStartPos += offset;
7826
0
}
7827
7828
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
7829
0
{
7830
0
    ImGuiWindow* window = GetCurrentWindowRead();
7831
0
    SetWindowPos(window, pos, cond);
7832
0
}
7833
7834
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
7835
0
{
7836
0
    if (ImGuiWindow* window = FindWindowByName(name))
7837
0
        SetWindowPos(window, pos, cond);
7838
0
}
7839
7840
ImVec2 ImGui::GetWindowSize()
7841
0
{
7842
0
    ImGuiWindow* window = GetCurrentWindowRead();
7843
0
    return window->Size;
7844
0
}
7845
7846
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
7847
25.5k
{
7848
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7849
25.5k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
7850
21.3k
        return;
7851
7852
4.22k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7853
4.22k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7854
7855
    // Set
7856
4.22k
    ImVec2 old_size = window->SizeFull;
7857
4.22k
    window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
7858
4.22k
    window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
7859
4.22k
    if (size.x <= 0.0f)
7860
0
        window->AutoFitOnlyGrows = false;
7861
4.22k
    else
7862
4.22k
        window->SizeFull.x = IM_FLOOR(size.x);
7863
4.22k
    if (size.y <= 0.0f)
7864
0
        window->AutoFitOnlyGrows = false;
7865
4.22k
    else
7866
4.22k
        window->SizeFull.y = IM_FLOOR(size.y);
7867
4.22k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
7868
1.27k
        MarkIniSettingsDirty(window);
7869
4.22k
}
7870
7871
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
7872
0
{
7873
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
7874
0
}
7875
7876
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
7877
0
{
7878
0
    if (ImGuiWindow* window = FindWindowByName(name))
7879
0
        SetWindowSize(window, size, cond);
7880
0
}
7881
7882
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
7883
0
{
7884
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7885
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
7886
0
        return;
7887
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7888
7889
    // Set
7890
0
    window->Collapsed = collapsed;
7891
0
}
7892
7893
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
7894
0
{
7895
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
7896
0
    window->HitTestHoleSize = ImVec2ih(size);
7897
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
7898
0
}
7899
7900
void ImGui::SetWindowHiddendAndSkipItemsForCurrentFrame(ImGuiWindow* window)
7901
0
{
7902
0
    window->Hidden = window->SkipItems = true;
7903
0
    window->HiddenFramesCanSkipItems = 1;
7904
0
}
7905
7906
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
7907
0
{
7908
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
7909
0
}
7910
7911
bool ImGui::IsWindowCollapsed()
7912
0
{
7913
0
    ImGuiWindow* window = GetCurrentWindowRead();
7914
0
    return window->Collapsed;
7915
0
}
7916
7917
bool ImGui::IsWindowAppearing()
7918
0
{
7919
0
    ImGuiWindow* window = GetCurrentWindowRead();
7920
0
    return window->Appearing;
7921
0
}
7922
7923
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
7924
0
{
7925
0
    if (ImGuiWindow* window = FindWindowByName(name))
7926
0
        SetWindowCollapsed(window, collapsed, cond);
7927
0
}
7928
7929
void ImGui::SetWindowFocus()
7930
2.57k
{
7931
2.57k
    FocusWindow(GImGui->CurrentWindow);
7932
2.57k
}
7933
7934
void ImGui::SetWindowFocus(const char* name)
7935
0
{
7936
0
    if (name)
7937
0
    {
7938
0
        if (ImGuiWindow* window = FindWindowByName(name))
7939
0
            FocusWindow(window);
7940
0
    }
7941
0
    else
7942
0
    {
7943
0
        FocusWindow(NULL);
7944
0
    }
7945
0
}
7946
7947
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
7948
0
{
7949
0
    ImGuiContext& g = *GImGui;
7950
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7951
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
7952
0
    g.NextWindowData.PosVal = pos;
7953
0
    g.NextWindowData.PosPivotVal = pivot;
7954
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
7955
0
    g.NextWindowData.PosUndock = true;
7956
0
}
7957
7958
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
7959
25.5k
{
7960
25.5k
    ImGuiContext& g = *GImGui;
7961
25.5k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7962
25.5k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
7963
25.5k
    g.NextWindowData.SizeVal = size;
7964
25.5k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
7965
25.5k
}
7966
7967
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
7968
0
{
7969
0
    ImGuiContext& g = *GImGui;
7970
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
7971
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
7972
0
    g.NextWindowData.SizeCallback = custom_callback;
7973
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
7974
0
}
7975
7976
// Content size = inner scrollable rectangle, padded with WindowPadding.
7977
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
7978
void ImGui::SetNextWindowContentSize(const ImVec2& size)
7979
0
{
7980
0
    ImGuiContext& g = *GImGui;
7981
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
7982
0
    g.NextWindowData.ContentSizeVal = ImFloor(size);
7983
0
}
7984
7985
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
7986
0
{
7987
0
    ImGuiContext& g = *GImGui;
7988
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
7989
0
    g.NextWindowData.ScrollVal = scroll;
7990
0
}
7991
7992
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
7993
0
{
7994
0
    ImGuiContext& g = *GImGui;
7995
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7996
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
7997
0
    g.NextWindowData.CollapsedVal = collapsed;
7998
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
7999
0
}
8000
8001
void ImGui::SetNextWindowFocus()
8002
0
{
8003
0
    ImGuiContext& g = *GImGui;
8004
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8005
0
}
8006
8007
void ImGui::SetNextWindowBgAlpha(float alpha)
8008
0
{
8009
0
    ImGuiContext& g = *GImGui;
8010
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8011
0
    g.NextWindowData.BgAlphaVal = alpha;
8012
0
}
8013
8014
void ImGui::SetNextWindowViewport(ImGuiID id)
8015
0
{
8016
0
    ImGuiContext& g = *GImGui;
8017
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8018
0
    g.NextWindowData.ViewportId = id;
8019
0
}
8020
8021
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8022
0
{
8023
0
    ImGuiContext& g = *GImGui;
8024
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8025
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8026
0
    g.NextWindowData.DockId = id;
8027
0
}
8028
8029
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8030
0
{
8031
0
    ImGuiContext& g = *GImGui;
8032
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8033
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8034
0
    g.NextWindowData.WindowClass = *window_class;
8035
0
}
8036
8037
ImDrawList* ImGui::GetWindowDrawList()
8038
4.22k
{
8039
4.22k
    ImGuiWindow* window = GetCurrentWindow();
8040
4.22k
    return window->DrawList;
8041
4.22k
}
8042
8043
float ImGui::GetWindowDpiScale()
8044
0
{
8045
0
    ImGuiContext& g = *GImGui;
8046
0
    return g.CurrentDpiScale;
8047
0
}
8048
8049
ImGuiViewport* ImGui::GetWindowViewport()
8050
0
{
8051
0
    ImGuiContext& g = *GImGui;
8052
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8053
0
    return g.CurrentViewport;
8054
0
}
8055
8056
ImFont* ImGui::GetFont()
8057
59.4k
{
8058
59.4k
    return GImGui->Font;
8059
59.4k
}
8060
8061
float ImGui::GetFontSize()
8062
59.5k
{
8063
59.5k
    return GImGui->FontSize;
8064
59.5k
}
8065
8066
ImVec2 ImGui::GetFontTexUvWhitePixel()
8067
0
{
8068
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8069
0
}
8070
8071
void ImGui::SetWindowFontScale(float scale)
8072
0
{
8073
0
    IM_ASSERT(scale > 0.0f);
8074
0
    ImGuiContext& g = *GImGui;
8075
0
    ImGuiWindow* window = GetCurrentWindow();
8076
0
    window->FontWindowScale = scale;
8077
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8078
0
}
8079
8080
void ImGui::ActivateItem(ImGuiID id)
8081
0
{
8082
0
    ImGuiContext& g = *GImGui;
8083
0
    g.NavNextActivateId = id;
8084
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8085
0
}
8086
8087
void ImGui::PushFocusScope(ImGuiID id)
8088
46.9k
{
8089
46.9k
    ImGuiContext& g = *GImGui;
8090
46.9k
    g.FocusScopeStack.push_back(id);
8091
46.9k
    g.CurrentFocusScopeId = id;
8092
46.9k
}
8093
8094
void ImGui::PopFocusScope()
8095
46.9k
{
8096
46.9k
    ImGuiContext& g = *GImGui;
8097
46.9k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
8098
46.9k
    g.FocusScopeStack.pop_back();
8099
46.9k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8100
46.9k
}
8101
8102
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8103
void ImGui::SetKeyboardFocusHere(int offset)
8104
0
{
8105
0
    ImGuiContext& g = *GImGui;
8106
0
    ImGuiWindow* window = g.CurrentWindow;
8107
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8108
0
    IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8109
8110
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8111
    // When we refactor this function into ActivateItem() we may want to make this an option.
8112
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8113
    // is also automatically dropped in the event g.ActiveId is stolen.
8114
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8115
0
    {
8116
0
        IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8117
0
        return;
8118
0
    }
8119
8120
0
    SetNavWindow(window);
8121
8122
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8123
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8124
0
    if (offset == -1)
8125
0
    {
8126
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8127
0
    }
8128
0
    else
8129
0
    {
8130
0
        g.NavTabbingDir = 1;
8131
0
        g.NavTabbingCounter = offset + 1;
8132
0
    }
8133
0
}
8134
8135
void ImGui::SetItemDefaultFocus()
8136
0
{
8137
0
    ImGuiContext& g = *GImGui;
8138
0
    ImGuiWindow* window = g.CurrentWindow;
8139
0
    if (!window->Appearing)
8140
0
        return;
8141
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8142
0
        return;
8143
8144
0
    g.NavInitRequest = false;
8145
0
    g.NavInitResultId = g.LastItemData.ID;
8146
0
    g.NavInitResultRectRel = WindowRectAbsToRel(window, g.LastItemData.Rect);
8147
0
    NavUpdateAnyRequestFlag();
8148
8149
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8150
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8151
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8152
0
}
8153
8154
void ImGui::SetStateStorage(ImGuiStorage* tree)
8155
0
{
8156
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8157
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8158
0
}
8159
8160
ImGuiStorage* ImGui::GetStateStorage()
8161
0
{
8162
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8163
0
    return window->DC.StateStorage;
8164
0
}
8165
8166
void ImGui::PushID(const char* str_id)
8167
4.21k
{
8168
4.21k
    ImGuiContext& g = *GImGui;
8169
4.21k
    ImGuiWindow* window = g.CurrentWindow;
8170
4.21k
    ImGuiID id = window->GetID(str_id);
8171
4.21k
    window->IDStack.push_back(id);
8172
4.21k
}
8173
8174
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8175
0
{
8176
0
    ImGuiContext& g = *GImGui;
8177
0
    ImGuiWindow* window = g.CurrentWindow;
8178
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8179
0
    window->IDStack.push_back(id);
8180
0
}
8181
8182
void ImGui::PushID(const void* ptr_id)
8183
0
{
8184
0
    ImGuiContext& g = *GImGui;
8185
0
    ImGuiWindow* window = g.CurrentWindow;
8186
0
    ImGuiID id = window->GetID(ptr_id);
8187
0
    window->IDStack.push_back(id);
8188
0
}
8189
8190
void ImGui::PushID(int int_id)
8191
0
{
8192
0
    ImGuiContext& g = *GImGui;
8193
0
    ImGuiWindow* window = g.CurrentWindow;
8194
0
    ImGuiID id = window->GetID(int_id);
8195
0
    window->IDStack.push_back(id);
8196
0
}
8197
8198
// Push a given id value ignoring the ID stack as a seed.
8199
void ImGui::PushOverrideID(ImGuiID id)
8200
0
{
8201
0
    ImGuiContext& g = *GImGui;
8202
0
    ImGuiWindow* window = g.CurrentWindow;
8203
0
    if (g.DebugHookIdInfo == id)
8204
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8205
0
    window->IDStack.push_back(id);
8206
0
}
8207
8208
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8209
// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
8210
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8211
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8212
0
{
8213
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8214
0
    ImGuiContext& g = *GImGui;
8215
0
    if (g.DebugHookIdInfo == id)
8216
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8217
0
    return id;
8218
0
}
8219
8220
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8221
0
{
8222
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8223
0
    ImGuiContext& g = *GImGui;
8224
0
    if (g.DebugHookIdInfo == id)
8225
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8226
0
    return id;
8227
0
}
8228
8229
void ImGui::PopID()
8230
4.21k
{
8231
4.21k
    ImGuiWindow* window = GImGui->CurrentWindow;
8232
4.21k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8233
4.21k
    window->IDStack.pop_back();
8234
4.21k
}
8235
8236
ImGuiID ImGui::GetID(const char* str_id)
8237
0
{
8238
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8239
0
    return window->GetID(str_id);
8240
0
}
8241
8242
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8243
0
{
8244
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8245
0
    return window->GetID(str_id_begin, str_id_end);
8246
0
}
8247
8248
ImGuiID ImGui::GetID(const void* ptr_id)
8249
0
{
8250
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8251
0
    return window->GetID(ptr_id);
8252
0
}
8253
8254
bool ImGui::IsRectVisible(const ImVec2& size)
8255
0
{
8256
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8257
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8258
0
}
8259
8260
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8261
0
{
8262
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8263
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8264
0
}
8265
8266
8267
//-----------------------------------------------------------------------------
8268
// [SECTION] INPUTS
8269
//-----------------------------------------------------------------------------
8270
// - GetKeyData() [Internal]
8271
// - GetKeyIndex() [Internal]
8272
// - GetKeyName()
8273
// - GetKeyChordName() [Internal]
8274
// - CalcTypematicRepeatAmount() [Internal]
8275
// - GetTypematicRepeatRate() [Internal]
8276
// - GetKeyPressedAmount() [Internal]
8277
// - GetKeyMagnitude2d() [Internal]
8278
//-----------------------------------------------------------------------------
8279
// - UpdateKeyRoutingTable() [Internal]
8280
// - GetRoutingIdFromOwnerId() [Internal]
8281
// - GetShortcutRoutingData() [Internal]
8282
// - CalcRoutingScore() [Internal]
8283
// - SetShortcutRouting() [Internal]
8284
// - TestShortcutRouting() [Internal]
8285
//-----------------------------------------------------------------------------
8286
// - IsKeyDown()
8287
// - IsKeyPressed()
8288
// - IsKeyReleased()
8289
//-----------------------------------------------------------------------------
8290
// - IsMouseDown()
8291
// - IsMouseClicked()
8292
// - IsMouseReleased()
8293
// - IsMouseDoubleClicked()
8294
// - GetMouseClickedCount()
8295
// - IsMouseHoveringRect() [Internal]
8296
// - IsMouseDragPastThreshold() [Internal]
8297
// - IsMouseDragging()
8298
// - GetMousePos()
8299
// - GetMousePosOnOpeningCurrentPopup()
8300
// - IsMousePosValid()
8301
// - IsAnyMouseDown()
8302
// - GetMouseDragDelta()
8303
// - ResetMouseDragDelta()
8304
// - GetMouseCursor()
8305
// - SetMouseCursor()
8306
//-----------------------------------------------------------------------------
8307
// - UpdateAliasKey()
8308
// - GetMergedModsFromKeys()
8309
// - UpdateKeyboardInputs()
8310
// - UpdateMouseInputs()
8311
//-----------------------------------------------------------------------------
8312
// - LockWheelingWindow [Internal]
8313
// - FindBestWheelingWindow [Internal]
8314
// - UpdateMouseWheel() [Internal]
8315
//-----------------------------------------------------------------------------
8316
// - SetNextFrameWantCaptureKeyboard()
8317
// - SetNextFrameWantCaptureMouse()
8318
//-----------------------------------------------------------------------------
8319
// - GetInputSourceName() [Internal]
8320
// - DebugPrintInputEvent() [Internal]
8321
// - UpdateInputEvents() [Internal]
8322
//-----------------------------------------------------------------------------
8323
// - GetKeyOwner() [Internal]
8324
// - TestKeyOwner() [Internal]
8325
// - SetKeyOwner() [Internal]
8326
// - SetItemKeyOwner() [Internal]
8327
// - Shortcut() [Internal]
8328
//-----------------------------------------------------------------------------
8329
8330
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8331
563k
{
8332
563k
    ImGuiContext& g = *ctx;
8333
8334
    // Special storage location for mods
8335
563k
    if (key & ImGuiMod_Mask_)
8336
192k
        key = ConvertSingleModFlagToKey(ctx, key);
8337
8338
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8339
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8340
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8341
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
8342
#else
8343
563k
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8344
563k
#endif
8345
563k
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8346
563k
}
8347
8348
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8349
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8350
{
8351
    ImGuiContext& g = *GImGui;
8352
    IM_ASSERT(IsNamedKey(key));
8353
    const ImGuiKeyData* key_data = GetKeyData(key);
8354
    return (ImGuiKey)(key_data - g.IO.KeysData);
8355
}
8356
#endif
8357
8358
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8359
static const char* const GKeyNames[] =
8360
{
8361
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8362
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8363
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8364
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8365
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8366
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8367
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8368
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8369
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8370
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8371
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8372
    "GamepadStart", "GamepadBack",
8373
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8374
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8375
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8376
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8377
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8378
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8379
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8380
};
8381
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8382
8383
const char* ImGui::GetKeyName(ImGuiKey key)
8384
0
{
8385
0
    ImGuiContext& g = *GImGui;
8386
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8387
0
    IM_ASSERT((IsNamedKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8388
#else
8389
    if (IsLegacyKey(key))
8390
    {
8391
        if (g.IO.KeyMap[key] == -1)
8392
            return "N/A";
8393
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8394
        key = (ImGuiKey)g.IO.KeyMap[key];
8395
    }
8396
#endif
8397
0
    if (key == ImGuiKey_None)
8398
0
        return "None";
8399
0
    if (key & ImGuiMod_Mask_)
8400
0
        key = ConvertSingleModFlagToKey(&g, key);
8401
0
    if (!IsNamedKey(key))
8402
0
        return "Unknown";
8403
8404
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8405
0
}
8406
8407
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8408
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8409
0
{
8410
0
    ImGuiContext& g = *GImGui;
8411
0
    if (key_chord & ImGuiMod_Shortcut)
8412
0
        key_chord = ConvertShortcutMod(key_chord);
8413
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8414
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8415
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8416
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8417
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8418
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8419
0
}
8420
8421
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8422
// t1 = current time (e.g.: g.Time)
8423
// An event is triggered at:
8424
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8425
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8426
66
{
8427
66
    if (t1 == 0.0f)
8428
0
        return 1;
8429
66
    if (t0 >= t1)
8430
0
        return 0;
8431
66
    if (repeat_rate <= 0.0f)
8432
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8433
66
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8434
66
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8435
66
    const int count = count_t1 - count_t0;
8436
66
    return count;
8437
66
}
8438
8439
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8440
588
{
8441
588
    ImGuiContext& g = *GImGui;
8442
588
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8443
588
    {
8444
43
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8445
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8446
545
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8447
588
    }
8448
588
}
8449
8450
// Return value representing the number of presses in the last time period, for the given repeat rate
8451
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8452
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8453
66
{
8454
66
    ImGuiContext& g = *GImGui;
8455
66
    const ImGuiKeyData* key_data = GetKeyData(key);
8456
66
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8457
0
        return 0;
8458
66
    const float t = key_data->DownDuration;
8459
66
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8460
66
}
8461
8462
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8463
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8464
0
{
8465
0
    return ImVec2(
8466
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8467
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8468
0
}
8469
8470
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8471
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8472
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8473
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8474
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8475
21.3k
{
8476
21.3k
    ImGuiContext& g = *GImGui;
8477
21.3k
    rt->EntriesNext.resize(0);
8478
3.01M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8479
2.99M
    {
8480
2.99M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8481
2.99M
        ImGuiKeyRoutingData* routing_entry;
8482
2.99M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8483
0
        {
8484
0
            routing_entry = &rt->Entries[old_routing_idx];
8485
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8486
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8487
0
            routing_entry->RoutingNextScore = 255;
8488
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8489
0
                continue;
8490
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8491
8492
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8493
0
            if (routing_entry->Mods == g.IO.KeyMods)
8494
0
            {
8495
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
8496
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8497
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8498
0
            }
8499
0
        }
8500
8501
        // Rewrite linked-list
8502
2.99M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8503
2.99M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8504
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8505
2.99M
    }
8506
21.3k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8507
21.3k
}
8508
8509
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8510
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8511
0
{
8512
0
    ImGuiContext& g = *GImGui;
8513
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8514
0
}
8515
8516
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8517
0
{
8518
    // Majority of shortcuts will be Key + any number of Mods
8519
    // We accept _Single_ mod with ImGuiKey_None.
8520
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8521
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8522
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8523
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8524
0
    ImGuiContext& g = *GImGui;
8525
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8526
0
    ImGuiKeyRoutingData* routing_data;
8527
0
    if (key_chord & ImGuiMod_Shortcut)
8528
0
        key_chord = ConvertShortcutMod(key_chord);
8529
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8530
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8531
0
    if (key == ImGuiKey_None)
8532
0
        key = ConvertSingleModFlagToKey(&g, mods);
8533
0
    IM_ASSERT(IsNamedKey(key));
8534
8535
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8536
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8537
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8538
0
    {
8539
0
        routing_data = &rt->Entries[idx];
8540
0
        if (routing_data->Mods == mods)
8541
0
            return routing_data;
8542
0
    }
8543
8544
    // Add to linked-list
8545
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8546
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8547
0
    routing_data = &rt->Entries[routing_data_idx];
8548
0
    routing_data->Mods = (ImU16)mods;
8549
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8550
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8551
0
    return routing_data;
8552
0
}
8553
8554
// Current score encoding (lower is highest priority):
8555
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8556
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8557
//  -   2: ImGuiInputFlags_RouteGlobal
8558
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8559
//  - 254: ImGuiInputFlags_RouteGlobalLow
8560
//  - 255: never route
8561
// 'flags' should include an explicit routing policy
8562
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8563
0
{
8564
0
    if (flags & ImGuiInputFlags_RouteFocused)
8565
0
    {
8566
0
        ImGuiContext& g = *GImGui;
8567
0
        ImGuiWindow* focused = g.NavWindow;
8568
8569
        // ActiveID gets top priority
8570
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8571
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8572
0
            return 1;
8573
8574
        // Score based on distance to focused window (lower is better)
8575
        // Assuming both windows are submitting a routing request,
8576
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8577
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8578
        // Assuming only WindowA is submitting a routing request,
8579
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8580
0
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8581
0
            for (int next_score = 3; focused != NULL; next_score++)
8582
0
            {
8583
0
                if (focused == location)
8584
0
                {
8585
0
                    IM_ASSERT(next_score < 255);
8586
0
                    return next_score;
8587
0
                }
8588
0
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8589
0
            }
8590
0
        return 255;
8591
0
    }
8592
8593
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8594
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8595
0
        return 2;
8596
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8597
0
        return 254;
8598
0
    return 0;
8599
0
}
8600
8601
// Request a desired route for an input chord (key + mods).
8602
// Return true if the route is available this frame.
8603
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8604
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8605
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8606
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8607
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8608
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8609
42.7k
{
8610
42.7k
    ImGuiContext& g = *GImGui;
8611
42.7k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8612
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8613
42.7k
    else
8614
42.7k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8615
8616
42.7k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8617
0
        if (g.NavWindow == NULL)
8618
0
            return false;
8619
42.7k
    if (flags & ImGuiInputFlags_RouteAlways)
8620
42.7k
        return true;
8621
8622
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8623
0
    if (score == 255)
8624
0
        return false;
8625
8626
    // Submit routing for NEXT frame (assuming score is sufficient)
8627
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8628
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8629
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8630
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8631
0
    if (score < routing_data->RoutingNextScore)
8632
0
    {
8633
0
        routing_data->RoutingNext = routing_id;
8634
0
        routing_data->RoutingNextScore = (ImU8)score;
8635
0
    }
8636
8637
    // Return routing state for CURRENT frame
8638
0
    return routing_data->RoutingCurr == routing_id;
8639
0
}
8640
8641
// Currently unused by core (but used by tests)
8642
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8643
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8644
0
{
8645
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8646
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8647
0
    return routing_data->RoutingCurr == routing_id;
8648
0
}
8649
8650
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8651
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8652
bool ImGui::IsKeyDown(ImGuiKey key)
8653
320k
{
8654
320k
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8655
320k
}
8656
8657
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8658
325k
{
8659
325k
    const ImGuiKeyData* key_data = GetKeyData(key);
8660
325k
    if (!key_data->Down)
8661
320k
        return false;
8662
4.22k
    if (!TestKeyOwner(key, owner_id))
8663
11
        return false;
8664
4.21k
    return true;
8665
4.22k
}
8666
8667
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8668
27.1k
{
8669
27.1k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8670
27.1k
}
8671
8672
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8673
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
8674
85.2k
{
8675
85.2k
    const ImGuiKeyData* key_data = GetKeyData(key);
8676
85.2k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8677
83.0k
        return false;
8678
2.18k
    const float t = key_data->DownDuration;
8679
2.18k
    if (t < 0.0f)
8680
0
        return false;
8681
2.18k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8682
8683
2.18k
    bool pressed = (t == 0.0f);
8684
2.18k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
8685
588
    {
8686
588
        float repeat_delay, repeat_rate;
8687
588
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
8688
588
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
8689
588
    }
8690
2.18k
    if (!pressed)
8691
1.77k
        return false;
8692
406
    if (!TestKeyOwner(key, owner_id))
8693
0
        return false;
8694
406
    return true;
8695
406
}
8696
8697
bool ImGui::IsKeyReleased(ImGuiKey key)
8698
0
{
8699
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
8700
0
}
8701
8702
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
8703
0
{
8704
0
    const ImGuiKeyData* key_data = GetKeyData(key);
8705
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
8706
0
        return false;
8707
0
    if (!TestKeyOwner(key, owner_id))
8708
0
        return false;
8709
0
    return true;
8710
0
}
8711
8712
bool ImGui::IsMouseDown(ImGuiMouseButton button)
8713
0
{
8714
0
    ImGuiContext& g = *GImGui;
8715
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8716
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
8717
0
}
8718
8719
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
8720
203
{
8721
203
    ImGuiContext& g = *GImGui;
8722
203
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8723
203
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
8724
203
}
8725
8726
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
8727
63
{
8728
63
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8729
63
}
8730
8731
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
8732
1.01k
{
8733
1.01k
    ImGuiContext& g = *GImGui;
8734
1.01k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8735
1.01k
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8736
723
        return false;
8737
289
    const float t = g.IO.MouseDownDuration[button];
8738
289
    if (t < 0.0f)
8739
0
        return false;
8740
289
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8741
8742
289
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
8743
289
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
8744
289
    if (!pressed)
8745
240
        return false;
8746
8747
49
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
8748
0
        return false;
8749
8750
49
    return true;
8751
49
}
8752
8753
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
8754
0
{
8755
0
    ImGuiContext& g = *GImGui;
8756
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8757
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
8758
0
}
8759
8760
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
8761
949
{
8762
949
    ImGuiContext& g = *GImGui;
8763
949
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8764
949
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
8765
949
}
8766
8767
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
8768
63
{
8769
63
    ImGuiContext& g = *GImGui;
8770
63
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8771
63
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
8772
63
}
8773
8774
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
8775
0
{
8776
0
    ImGuiContext& g = *GImGui;
8777
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8778
0
    return g.IO.MouseClickedCount[button];
8779
0
}
8780
8781
// Test if mouse cursor is hovering given rectangle
8782
// NB- Rectangle is clipped by our current clip setting
8783
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
8784
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
8785
104k
{
8786
104k
    ImGuiContext& g = *GImGui;
8787
8788
    // Clip
8789
104k
    ImRect rect_clipped(r_min, r_max);
8790
104k
    if (clip)
8791
57.6k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
8792
8793
    // Expand for touch input
8794
104k
    const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
8795
104k
    if (!rect_for_touch.Contains(g.IO.MousePos))
8796
99.5k
        return false;
8797
5.11k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
8798
0
        return false;
8799
5.11k
    return true;
8800
5.11k
}
8801
8802
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
8803
// [Internal] This doesn't test if the button is pressed
8804
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
8805
208
{
8806
208
    ImGuiContext& g = *GImGui;
8807
208
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8808
208
    if (lock_threshold < 0.0f)
8809
208
        lock_threshold = g.IO.MouseDragThreshold;
8810
208
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
8811
208
}
8812
8813
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
8814
259
{
8815
259
    ImGuiContext& g = *GImGui;
8816
259
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8817
259
    if (!g.IO.MouseDown[button])
8818
51
        return false;
8819
208
    return IsMouseDragPastThreshold(button, lock_threshold);
8820
259
}
8821
8822
ImVec2 ImGui::GetMousePos()
8823
720
{
8824
720
    ImGuiContext& g = *GImGui;
8825
720
    return g.IO.MousePos;
8826
720
}
8827
8828
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
8829
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
8830
0
{
8831
0
    ImGuiContext& g = *GImGui;
8832
0
    if (g.BeginPopupStack.Size > 0)
8833
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
8834
0
    return g.IO.MousePos;
8835
0
}
8836
8837
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
8838
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
8839
58.1k
{
8840
    // The assert is only to silence a false-positive in XCode Static Analysis.
8841
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
8842
58.1k
    IM_ASSERT(GImGui != NULL);
8843
58.1k
    const float MOUSE_INVALID = -256000.0f;
8844
58.1k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
8845
58.1k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
8846
58.1k
}
8847
8848
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
8849
bool ImGui::IsAnyMouseDown()
8850
0
{
8851
0
    ImGuiContext& g = *GImGui;
8852
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
8853
0
        if (g.IO.MouseDown[n])
8854
0
            return true;
8855
0
    return false;
8856
0
}
8857
8858
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
8859
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
8860
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
8861
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
8862
0
{
8863
0
    ImGuiContext& g = *GImGui;
8864
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8865
0
    if (lock_threshold < 0.0f)
8866
0
        lock_threshold = g.IO.MouseDragThreshold;
8867
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
8868
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
8869
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
8870
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
8871
0
    return ImVec2(0.0f, 0.0f);
8872
0
}
8873
8874
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
8875
0
{
8876
0
    ImGuiContext& g = *GImGui;
8877
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8878
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
8879
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
8880
0
}
8881
8882
// Get desired mouse cursor shape.
8883
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
8884
// updated during the frame, and locked in EndFrame()/Render().
8885
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
8886
ImGuiMouseCursor ImGui::GetMouseCursor()
8887
0
{
8888
0
    ImGuiContext& g = *GImGui;
8889
0
    return g.MouseCursor;
8890
0
}
8891
8892
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
8893
27
{
8894
27
    ImGuiContext& g = *GImGui;
8895
27
    g.MouseCursor = cursor_type;
8896
27
}
8897
8898
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
8899
149k
{
8900
149k
    IM_ASSERT(ImGui::IsAliasKey(key));
8901
149k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
8902
149k
    key_data->Down = v;
8903
149k
    key_data->AnalogValue = analog_value;
8904
149k
}
8905
8906
// [Internal] Do not use directly
8907
static ImGuiKeyChord GetMergedModsFromKeys()
8908
42.7k
{
8909
42.7k
    ImGuiKeyChord mods = 0;
8910
42.7k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
8911
42.7k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
8912
42.7k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
8913
42.7k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
8914
42.7k
    return mods;
8915
42.7k
}
8916
8917
static void ImGui::UpdateKeyboardInputs()
8918
21.3k
{
8919
21.3k
    ImGuiContext& g = *GImGui;
8920
21.3k
    ImGuiIO& io = g.IO;
8921
8922
    // Import legacy keys or verify they are not used
8923
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8924
    if (io.BackendUsingLegacyKeyArrays == 0)
8925
    {
8926
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
8927
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
8928
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
8929
    }
8930
    else
8931
    {
8932
        if (g.FrameCount == 0)
8933
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
8934
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
8935
8936
        // Build reverse KeyMap (Named -> Legacy)
8937
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
8938
            if (io.KeyMap[n] != -1)
8939
            {
8940
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
8941
                io.KeyMap[io.KeyMap[n]] = n;
8942
            }
8943
8944
        // Import legacy keys into new ones
8945
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
8946
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
8947
            {
8948
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
8949
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
8950
                io.KeysData[key].Down = io.KeysDown[n];
8951
                if (key != n)
8952
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
8953
                io.BackendUsingLegacyKeyArrays = 1;
8954
            }
8955
        if (io.BackendUsingLegacyKeyArrays == 1)
8956
        {
8957
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
8958
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
8959
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
8960
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
8961
        }
8962
    }
8963
8964
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8965
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
8966
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
8967
    {
8968
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
8969
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
8970
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
8971
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
8972
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
8973
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
8974
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
8975
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
8976
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
8977
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
8978
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
8979
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
8980
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
8981
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
8982
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
8983
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
8984
        #undef NAV_MAP_KEY
8985
    }
8986
#endif
8987
#endif
8988
8989
    // Update aliases
8990
128k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
8991
106k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
8992
21.3k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
8993
21.3k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
8994
8995
    // Synchronize io.KeyMods and io.KeyXXX values.
8996
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
8997
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
8998
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
8999
21.3k
    io.KeyMods = GetMergedModsFromKeys();
9000
21.3k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9001
21.3k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9002
21.3k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9003
21.3k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9004
9005
    // Clear gamepad data if disabled
9006
21.3k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9007
534k
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9008
512k
        {
9009
512k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9010
512k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9011
512k
        }
9012
9013
    // Update keys
9014
3.01M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9015
2.99M
    {
9016
2.99M
        ImGuiKeyData* key_data = &io.KeysData[i];
9017
2.99M
        key_data->DownDurationPrev = key_data->DownDuration;
9018
2.99M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9019
2.99M
    }
9020
9021
    // Update keys/input owner (named keys only): one entry per key
9022
3.01M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9023
2.99M
    {
9024
2.99M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9025
2.99M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9026
2.99M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9027
2.99M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9028
2.97M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
9029
2.99M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9030
2.99M
    }
9031
9032
21.3k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9033
21.3k
}
9034
9035
static void ImGui::UpdateMouseInputs()
9036
21.3k
{
9037
21.3k
    ImGuiContext& g = *GImGui;
9038
21.3k
    ImGuiIO& io = g.IO;
9039
9040
    // Mouse Wheel swapping flag
9041
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9042
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9043
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9044
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9045
21.3k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9046
9047
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9048
21.3k
    if (IsMousePosValid(&io.MousePos))
9049
5.03k
        io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos);
9050
9051
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9052
21.3k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9053
4.52k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9054
16.8k
    else
9055
16.8k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9056
9057
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9058
21.3k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9059
151
        g.NavDisableMouseHover = false;
9060
9061
21.3k
    io.MousePosPrev = io.MousePos;
9062
128k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9063
106k
    {
9064
106k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9065
106k
        io.MouseClickedCount[i] = 0; // Will be filled below
9066
106k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9067
106k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9068
106k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9069
106k
        if (io.MouseClicked[i])
9070
864
        {
9071
864
            bool is_repeated_click = false;
9072
864
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9073
367
            {
9074
367
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9075
367
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9076
330
                    is_repeated_click = true;
9077
367
            }
9078
864
            if (is_repeated_click)
9079
330
                io.MouseClickedLastCount[i]++;
9080
534
            else
9081
534
                io.MouseClickedLastCount[i] = 1;
9082
864
            io.MouseClickedTime[i] = g.Time;
9083
864
            io.MouseClickedPos[i] = io.MousePos;
9084
864
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9085
864
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9086
864
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9087
864
        }
9088
105k
        else if (io.MouseDown[i])
9089
5.72k
        {
9090
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9091
5.72k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9092
5.72k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9093
5.72k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9094
5.72k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9095
5.72k
        }
9096
9097
        // We provide io.MouseDoubleClicked[] as a legacy service
9098
106k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9099
9100
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9101
106k
        if (io.MouseClicked[i])
9102
864
            g.NavDisableMouseHover = false;
9103
106k
    }
9104
21.3k
}
9105
9106
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9107
14
{
9108
14
    ImGuiContext& g = *GImGui;
9109
14
    if (window)
9110
7
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9111
7
    else
9112
7
        g.WheelingWindowReleaseTimer = 0.0f;
9113
14
    if (g.WheelingWindow == window)
9114
0
        return;
9115
14
    IMGUI_DEBUG_LOG_IO("LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9116
14
    g.WheelingWindow = window;
9117
14
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9118
14
    if (window == NULL)
9119
7
    {
9120
7
        g.WheelingWindowStartFrame = -1;
9121
7
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9122
7
    }
9123
14
}
9124
9125
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9126
12
{
9127
    // For each axis, find window in the hierarchy that may want to use scrolling
9128
12
    ImGuiContext& g = *GImGui;
9129
12
    ImGuiWindow* windows[2] = { NULL, NULL };
9130
36
    for (int axis = 0; axis < 2; axis++)
9131
24
        if (wheel[axis] != 0.0f)
9132
43
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9133
20
            {
9134
                // Bubble up into parent window if:
9135
                // - a child window doesn't allow any scrolling.
9136
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9137
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9138
20
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9139
20
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9140
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9141
20
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9142
0
                    break; // select this window
9143
20
            }
9144
12
    if (windows[0] == NULL && windows[1] == NULL)
9145
0
        return NULL;
9146
9147
    // If there's only one window or only one axis then there's no ambiguity
9148
12
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9149
12
        return windows[1] ? windows[1] : windows[0];
9150
9151
    // If candidate are different windows we need to decide which one to prioritize
9152
    // - First frame: only find a winner if one axis is zero.
9153
    // - Subsequent frames: only find a winner when one is more than the other.
9154
0
    if (g.WheelingWindowStartFrame == -1)
9155
0
        g.WheelingWindowStartFrame = g.FrameCount;
9156
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9157
0
    {
9158
0
        g.WheelingWindowWheelRemainder = wheel;
9159
0
        return NULL;
9160
0
    }
9161
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9162
0
}
9163
9164
// Called by NewFrame()
9165
void ImGui::UpdateMouseWheel()
9166
21.3k
{
9167
    // Reset the locked window if we move the mouse or after the timer elapses.
9168
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9169
21.3k
    ImGuiContext& g = *GImGui;
9170
21.3k
    if (g.WheelingWindow != NULL)
9171
7
    {
9172
7
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9173
7
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9174
1
            g.WheelingWindowReleaseTimer = 0.0f;
9175
7
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9176
7
            LockWheelingWindow(NULL, 0.0f);
9177
7
    }
9178
9179
21.3k
    ImVec2 wheel;
9180
21.3k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9181
21.3k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9182
9183
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9184
21.3k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9185
21.3k
    if (!mouse_window || mouse_window->Collapsed)
9186
21.1k
        return;
9187
9188
    // Zoom / Scale window
9189
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9190
235
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9191
0
    {
9192
0
        LockWheelingWindow(mouse_window, wheel.y);
9193
0
        ImGuiWindow* window = mouse_window;
9194
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9195
0
        const float scale = new_font_scale / window->FontWindowScale;
9196
0
        window->FontWindowScale = new_font_scale;
9197
0
        if (window == window->RootWindow)
9198
0
        {
9199
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9200
0
            SetWindowPos(window, window->Pos + offset, 0);
9201
0
            window->Size = ImFloor(window->Size * scale);
9202
0
            window->SizeFull = ImFloor(window->SizeFull * scale);
9203
0
        }
9204
0
        return;
9205
0
    }
9206
235
    if (g.IO.KeyCtrl)
9207
0
        return;
9208
9209
    // Mouse wheel scrolling
9210
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9211
235
    if (g.IO.MouseWheelRequestAxisSwap)
9212
0
        wheel = ImVec2(wheel.y, 0.0f);
9213
9214
    // Maintain a rough average of moving magnitude on both axises
9215
    // FIXME: should by based on wall clock time rather than frame-counter
9216
235
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9217
235
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9218
9219
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9220
235
    wheel += g.WheelingWindowWheelRemainder;
9221
235
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9222
235
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9223
223
        return;
9224
9225
    // Mouse wheel scrolling: find target and apply
9226
    // - don't renew lock if axis doesn't apply on the window.
9227
    // - select a main axis when both axises are being moved.
9228
12
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9229
12
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9230
12
        {
9231
12
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9232
12
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9233
6
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9234
12
            if (do_scroll[ImGuiAxis_X])
9235
3
            {
9236
3
                LockWheelingWindow(window, wheel.x);
9237
3
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9238
3
                float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
9239
3
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9240
3
            }
9241
12
            if (do_scroll[ImGuiAxis_Y])
9242
4
            {
9243
4
                LockWheelingWindow(window, wheel.y);
9244
4
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9245
4
                float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
9246
4
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9247
4
            }
9248
12
        }
9249
12
}
9250
9251
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9252
0
{
9253
0
    ImGuiContext& g = *GImGui;
9254
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9255
0
}
9256
9257
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9258
0
{
9259
0
    ImGuiContext& g = *GImGui;
9260
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9261
0
}
9262
9263
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9264
static const char* GetInputSourceName(ImGuiInputSource source)
9265
0
{
9266
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Clipboard" };
9267
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9268
0
    return input_source_names[source];
9269
0
}
9270
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9271
0
{
9272
0
    ImGuiContext& g = *GImGui;
9273
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("%s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("%s: MousePos (%.1f, %.1f)\n", prefix, e->MousePos.PosX, e->MousePos.PosY); return; }
9274
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("%s: MouseButton %d %s\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up"); return; }
9275
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("%s: MouseWheel (%.3f, %.3f)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY); return; }
9276
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("%s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9277
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("%s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9278
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("%s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9279
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("%s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9280
0
}
9281
#endif
9282
9283
// Process input queue
9284
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9285
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9286
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9287
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9288
21.3k
{
9289
21.3k
    ImGuiContext& g = *GImGui;
9290
21.3k
    ImGuiIO& io = g.IO;
9291
9292
    // Only trickle chars<>key when working with InputText()
9293
    // FIXME: InputText() could parse event trail?
9294
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9295
21.3k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9296
9297
21.3k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9298
21.3k
    int  mouse_button_changed = 0x00;
9299
21.3k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9300
9301
21.3k
    int event_n = 0;
9302
27.9k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9303
7.66k
    {
9304
7.66k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9305
7.66k
        if (e->Type == ImGuiInputEventType_MousePos)
9306
1.12k
        {
9307
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9308
1.12k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9309
1.12k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9310
219
                break;
9311
901
            io.MousePos = event_pos;
9312
901
            mouse_moved = true;
9313
901
        }
9314
6.54k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9315
1.43k
        {
9316
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9317
1.43k
            const ImGuiMouseButton button = e->MouseButton.Button;
9318
1.43k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9319
1.43k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9320
316
                break;
9321
1.12k
            io.MouseDown[button] = e->MouseButton.Down;
9322
1.12k
            mouse_button_changed |= (1 << button);
9323
1.12k
        }
9324
5.10k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9325
326
        {
9326
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9327
326
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9328
76
                break;
9329
250
            io.MouseWheelH += e->MouseWheel.WheelX;
9330
250
            io.MouseWheel += e->MouseWheel.WheelY;
9331
250
            mouse_wheeled = true;
9332
250
        }
9333
4.78k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9334
0
        {
9335
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9336
0
        }
9337
4.78k
        else if (e->Type == ImGuiInputEventType_Key)
9338
1.51k
        {
9339
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9340
1.51k
            ImGuiKey key = e->Key.Key;
9341
1.51k
            IM_ASSERT(key != ImGuiKey_None);
9342
1.51k
            ImGuiKeyData* key_data = GetKeyData(key);
9343
1.51k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9344
1.51k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9345
368
                break;
9346
1.14k
            key_data->Down = e->Key.Down;
9347
1.14k
            key_data->AnalogValue = e->Key.AnalogValue;
9348
1.14k
            key_changed = true;
9349
1.14k
            key_changed_mask.SetBit(key_data_index);
9350
9351
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9352
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9353
            io.KeysDown[key_data_index] = key_data->Down;
9354
            if (io.KeyMap[key_data_index] != -1)
9355
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9356
#endif
9357
1.14k
        }
9358
3.26k
        else if (e->Type == ImGuiInputEventType_Text)
9359
3.01k
        {
9360
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9361
3.01k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9362
91
                break;
9363
2.92k
            unsigned int c = e->Text.Char;
9364
2.92k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9365
2.92k
            if (trickle_interleaved_keys_and_text)
9366
0
                text_inputted = true;
9367
2.92k
        }
9368
252
        else if (e->Type == ImGuiInputEventType_Focus)
9369
252
        {
9370
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9371
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9372
252
            const bool focus_lost = !e->AppFocused.Focused;
9373
252
            io.AppFocusLost = focus_lost;
9374
252
        }
9375
0
        else
9376
0
        {
9377
0
            IM_ASSERT(0 && "Unknown event!");
9378
0
        }
9379
7.66k
    }
9380
9381
    // Record trail (for domain-specific applications wanting to access a precise trail)
9382
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9383
27.9k
    for (int n = 0; n < event_n; n++)
9384
6.59k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9385
9386
    // [DEBUG]
9387
21.3k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9388
21.3k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9389
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9390
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9391
21.3k
#endif
9392
9393
    // Remaining events will be processed on the next frame
9394
21.3k
    if (event_n == g.InputEventsQueue.Size)
9395
20.2k
        g.InputEventsQueue.resize(0);
9396
1.07k
    else
9397
1.07k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9398
9399
    // Clear buttons state when focus is lost
9400
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9401
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9402
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9403
21.3k
    if (g.IO.AppFocusLost)
9404
152
        g.IO.ClearInputKeys();
9405
21.3k
}
9406
9407
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9408
0
{
9409
0
    if (!IsNamedKeyOrModKey(key))
9410
0
        return ImGuiKeyOwner_None;
9411
9412
0
    ImGuiContext& g = *GImGui;
9413
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9414
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9415
9416
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9417
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9418
0
            return ImGuiKeyOwner_None;
9419
9420
0
    return owner_id;
9421
0
}
9422
9423
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9424
// TestKeyOwner(..., None) : (owner == None)
9425
// TestKeyOwner(..., Any)  : no owner test
9426
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9427
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9428
47.6k
{
9429
47.6k
    if (!IsNamedKeyOrModKey(key))
9430
0
        return true;
9431
9432
47.6k
    ImGuiContext& g = *GImGui;
9433
47.6k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9434
33
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9435
11
            return false;
9436
9437
47.6k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9438
47.6k
    if (owner_id == ImGuiKeyOwner_Any)
9439
3.99k
        return (owner_data->LockThisFrame == false);
9440
9441
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9442
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9443
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9444
43.6k
    if (owner_data->OwnerCurr != owner_id)
9445
42
    {
9446
42
        if (owner_data->LockThisFrame)
9447
0
            return false;
9448
42
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9449
0
            return false;
9450
42
    }
9451
9452
43.6k
    return true;
9453
43.6k
}
9454
9455
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9456
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9457
// - SetKeyOwner(..., None)              : clears owner
9458
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9459
// - SetKeyOwner(..., Any or None, Lock) : set lock
9460
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9461
42
{
9462
42
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9463
42
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9464
9465
42
    ImGuiContext& g = *GImGui;
9466
42
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9467
42
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9468
9469
    // We cannot lock by default as it would likely break lots of legacy code.
9470
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9471
42
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9472
42
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9473
42
}
9474
9475
// Rarely used helper
9476
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9477
0
{
9478
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
9479
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
9480
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
9481
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
9482
0
    if (key_chord & ImGuiMod_Shortcut)  { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
9483
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
9484
0
}
9485
9486
// This is more or less equivalent to:
9487
//   if (IsItemHovered() || IsItemActive())
9488
//       SetKeyOwner(key, GetItemID());
9489
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9490
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9491
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9492
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9493
0
{
9494
0
    ImGuiContext& g = *GImGui;
9495
0
    ImGuiID id = g.LastItemData.ID;
9496
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9497
0
        return;
9498
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9499
0
        flags |= ImGuiInputFlags_CondDefault_;
9500
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9501
0
    {
9502
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9503
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9504
0
    }
9505
0
}
9506
9507
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9508
42.7k
{
9509
42.7k
    ImGuiContext& g = *GImGui;
9510
9511
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9512
42.7k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9513
42.7k
        flags |= ImGuiInputFlags_RouteFocused;
9514
42.7k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9515
0
        return false;
9516
9517
42.7k
    if (key_chord & ImGuiMod_Shortcut)
9518
0
        key_chord = ConvertShortcutMod(key_chord);
9519
42.7k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9520
42.7k
    if (g.IO.KeyMods != mods)
9521
42.7k
        return false;
9522
9523
    // Special storage location for mods
9524
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9525
0
    if (key == ImGuiKey_None)
9526
0
        key = ConvertSingleModFlagToKey(&g, mods);
9527
9528
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9529
0
        return false;
9530
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9531
9532
0
    return true;
9533
0
}
9534
9535
9536
//-----------------------------------------------------------------------------
9537
// [SECTION] ERROR CHECKING
9538
//-----------------------------------------------------------------------------
9539
9540
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9541
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9542
// If this triggers you have an issue:
9543
// - Most commonly: mismatched headers and compiled code version.
9544
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9545
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9546
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9547
//   Otherwise it is possible that different compilation units would see different structure layout
9548
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9549
1
{
9550
1
    bool error = false;
9551
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9552
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9553
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9554
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9555
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9556
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9557
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9558
1
    return !error;
9559
1
}
9560
9561
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9562
// This is causing issues and ambiguity and we need to retire that.
9563
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9564
// [Scenario 1]
9565
//  Previously this would make the window content size ~200x200:
9566
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9567
//  Instead, please submit an item:
9568
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9569
//  Alternative:
9570
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9571
// [Scenario 2]
9572
//  For reference this is one of the issue what we aim to fix with this change:
9573
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9574
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9575
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9576
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9577
0
{
9578
0
    ImGuiContext& g = *GImGui;
9579
0
    ImGuiWindow* window = g.CurrentWindow;
9580
0
    IM_ASSERT(window->DC.IsSetPos);
9581
0
    window->DC.IsSetPos = false;
9582
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9583
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9584
0
        return;
9585
0
    if (window->SkipItems)
9586
0
        return;
9587
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9588
#else
9589
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9590
#endif
9591
0
}
9592
9593
static void ImGui::ErrorCheckNewFrameSanityChecks()
9594
21.3k
{
9595
21.3k
    ImGuiContext& g = *GImGui;
9596
9597
    // Check user IM_ASSERT macro
9598
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9599
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9600
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9601
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9602
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9603
21.3k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9604
9605
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
9606
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
9607
#ifdef __EMSCRIPTEN__
9608
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
9609
        g.IO.DeltaTime = 0.00001f;
9610
#endif
9611
9612
    // Check user data
9613
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9614
21.3k
    IM_ASSERT(g.Initialized);
9615
21.3k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9616
21.3k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9617
21.3k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9618
21.3k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9619
21.3k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9620
21.3k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
9621
21.3k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
9622
21.3k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
9623
21.3k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
9624
21.3k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
9625
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9626
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
9627
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
9628
9629
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
9630
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
9631
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
9632
#endif
9633
9634
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
9635
21.3k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
9636
1
        g.IO.ConfigWindowsResizeFromEdges = false;
9637
9638
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
9639
21.3k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
9640
21.3k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9641
21.3k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
9642
21.3k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9643
9644
    // Perform simple checks: multi-viewport and platform windows support
9645
21.3k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
9646
1
    {
9647
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
9648
0
        {
9649
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
9650
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
9651
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
9652
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
9653
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
9654
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
9655
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
9656
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
9657
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
9658
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
9659
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
9660
0
        }
9661
1
        else
9662
1
        {
9663
            // Disable feature, our backends do not support it
9664
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
9665
1
        }
9666
9667
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
9668
1
        for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
9669
0
        {
9670
0
            ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
9671
0
            IM_UNUSED(mon);
9672
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
9673
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
9674
0
            IM_ASSERT(mon.DpiScale != 0.0f);
9675
0
        }
9676
1
    }
9677
21.3k
}
9678
9679
static void ImGui::ErrorCheckEndFrameSanityChecks()
9680
21.3k
{
9681
21.3k
    ImGuiContext& g = *GImGui;
9682
9683
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
9684
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
9685
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
9686
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
9687
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
9688
    // while still correctly asserting on mid-frame key press events.
9689
21.3k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
9690
21.3k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
9691
21.3k
    IM_UNUSED(key_mods);
9692
9693
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
9694
    //ErrorCheckEndFrameRecover();
9695
9696
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
9697
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
9698
21.3k
    if (g.CurrentWindowStack.Size != 1)
9699
0
    {
9700
0
        if (g.CurrentWindowStack.Size > 1)
9701
0
        {
9702
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
9703
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
9704
0
            IM_UNUSED(window);
9705
0
            while (g.CurrentWindowStack.Size > 1)
9706
0
                End();
9707
0
        }
9708
0
        else
9709
0
        {
9710
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
9711
0
        }
9712
0
    }
9713
9714
21.3k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
9715
21.3k
}
9716
9717
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
9718
// Must be called during or before EndFrame().
9719
// This is generally flawed as we are not necessarily End/Popping things in the right order.
9720
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
9721
// FIXME: Can't recover from interleaved BeginTabBar/Begin
9722
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9723
0
{
9724
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
9725
0
    ImGuiContext& g = *GImGui;
9726
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
9727
0
    {
9728
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
9729
0
        ImGuiWindow* window = g.CurrentWindow;
9730
0
        if (g.CurrentWindowStack.Size == 1)
9731
0
        {
9732
0
            IM_ASSERT(window->IsFallbackWindow);
9733
0
            break;
9734
0
        }
9735
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
9736
0
        {
9737
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
9738
0
            EndChild();
9739
0
        }
9740
0
        else
9741
0
        {
9742
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
9743
0
            End();
9744
0
        }
9745
0
    }
9746
0
}
9747
9748
// Must be called before End()/EndChild()
9749
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9750
0
{
9751
0
    ImGuiContext& g = *GImGui;
9752
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
9753
0
    {
9754
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
9755
0
        EndTable();
9756
0
    }
9757
9758
0
    ImGuiWindow* window = g.CurrentWindow;
9759
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
9760
0
    IM_ASSERT(window != NULL);
9761
0
    while (g.CurrentTabBar != NULL) //-V1044
9762
0
    {
9763
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
9764
0
        EndTabBar();
9765
0
    }
9766
0
    while (window->DC.TreeDepth > 0)
9767
0
    {
9768
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
9769
0
        TreePop();
9770
0
    }
9771
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
9772
0
    {
9773
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
9774
0
        EndGroup();
9775
0
    }
9776
0
    while (window->IDStack.Size > 1)
9777
0
    {
9778
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
9779
0
        PopID();
9780
0
    }
9781
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
9782
0
    {
9783
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
9784
0
        EndDisabled();
9785
0
    }
9786
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
9787
0
    {
9788
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
9789
0
        PopStyleColor();
9790
0
    }
9791
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
9792
0
    {
9793
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
9794
0
        PopItemFlag();
9795
0
    }
9796
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
9797
0
    {
9798
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
9799
0
        PopStyleVar();
9800
0
    }
9801
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
9802
0
    {
9803
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
9804
0
        PopFocusScope();
9805
0
    }
9806
0
}
9807
9808
// Save current stack sizes for later compare
9809
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
9810
46.9k
{
9811
46.9k
    ImGuiContext& g = *ctx;
9812
46.9k
    ImGuiWindow* window = g.CurrentWindow;
9813
46.9k
    SizeOfIDStack = (short)window->IDStack.Size;
9814
46.9k
    SizeOfColorStack = (short)g.ColorStack.Size;
9815
46.9k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
9816
46.9k
    SizeOfFontStack = (short)g.FontStack.Size;
9817
46.9k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
9818
46.9k
    SizeOfGroupStack = (short)g.GroupStack.Size;
9819
46.9k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
9820
46.9k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
9821
46.9k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
9822
46.9k
}
9823
9824
// Compare to detect usage errors
9825
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
9826
46.9k
{
9827
46.9k
    ImGuiContext& g = *ctx;
9828
46.9k
    ImGuiWindow* window = g.CurrentWindow;
9829
46.9k
    IM_UNUSED(window);
9830
9831
    // Window stacks
9832
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
9833
46.9k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
9834
9835
    // Global stacks
9836
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
9837
46.9k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
9838
46.9k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
9839
46.9k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
9840
46.9k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
9841
46.9k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
9842
46.9k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
9843
46.9k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
9844
46.9k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
9845
46.9k
}
9846
9847
9848
//-----------------------------------------------------------------------------
9849
// [SECTION] LAYOUT
9850
//-----------------------------------------------------------------------------
9851
// - ItemSize()
9852
// - ItemAdd()
9853
// - SameLine()
9854
// - GetCursorScreenPos()
9855
// - SetCursorScreenPos()
9856
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
9857
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
9858
// - GetCursorStartPos()
9859
// - Indent()
9860
// - Unindent()
9861
// - SetNextItemWidth()
9862
// - PushItemWidth()
9863
// - PushMultiItemsWidths()
9864
// - PopItemWidth()
9865
// - CalcItemWidth()
9866
// - CalcItemSize()
9867
// - GetTextLineHeight()
9868
// - GetTextLineHeightWithSpacing()
9869
// - GetFrameHeight()
9870
// - GetFrameHeightWithSpacing()
9871
// - GetContentRegionMax()
9872
// - GetContentRegionMaxAbs() [Internal]
9873
// - GetContentRegionAvail(),
9874
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
9875
// - BeginGroup()
9876
// - EndGroup()
9877
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
9878
//-----------------------------------------------------------------------------
9879
9880
// Advance cursor given item size for layout.
9881
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
9882
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
9883
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
9884
8.48k
{
9885
8.48k
    ImGuiContext& g = *GImGui;
9886
8.48k
    ImGuiWindow* window = g.CurrentWindow;
9887
8.48k
    if (window->SkipItems)
9888
0
        return;
9889
9890
    // We increase the height in this function to accommodate for baseline offset.
9891
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
9892
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
9893
8.48k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
9894
9895
8.48k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
9896
8.48k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
9897
9898
    // Always align ourselves on pixel boundaries
9899
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
9900
8.48k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
9901
8.48k
    window->DC.CursorPosPrevLine.y = line_y1;
9902
8.48k
    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
9903
8.48k
    window->DC.CursorPos.y = IM_FLOOR(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
9904
8.48k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
9905
8.48k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
9906
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
9907
9908
8.48k
    window->DC.PrevLineSize.y = line_height;
9909
8.48k
    window->DC.CurrLineSize.y = 0.0f;
9910
8.48k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
9911
8.48k
    window->DC.CurrLineTextBaseOffset = 0.0f;
9912
8.48k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
9913
9914
    // Horizontal layout mode
9915
8.48k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9916
0
        SameLine();
9917
8.48k
}
9918
9919
// Declare item bounding box for clipping and interaction.
9920
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
9921
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
9922
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
9923
60.6k
{
9924
60.6k
    ImGuiContext& g = *GImGui;
9925
60.6k
    ImGuiWindow* window = g.CurrentWindow;
9926
9927
    // Set item data
9928
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
9929
60.6k
    g.LastItemData.ID = id;
9930
60.6k
    g.LastItemData.Rect = bb;
9931
60.6k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
9932
60.6k
    g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;
9933
60.6k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
9934
9935
    // Directional navigation processing
9936
60.6k
    if (id != 0)
9937
55.8k
    {
9938
55.8k
        KeepAliveID(id);
9939
9940
        // Runs prior to clipping early-out
9941
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
9942
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
9943
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
9944
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
9945
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
9946
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
9947
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
9948
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
9949
55.8k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
9950
46.4k
        {
9951
46.4k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
9952
46.4k
            if (g.NavId == id || g.NavAnyRequest)
9953
203
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
9954
101
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
9955
101
                        NavProcessItem();
9956
46.4k
        }
9957
9958
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
9959
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
9960
        // READ THE FAQ: https://dearimgui.org/faq
9961
55.8k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
9962
55.8k
    }
9963
60.6k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
9964
9965
#ifdef IMGUI_ENABLE_TEST_ENGINE
9966
    if (id != 0)
9967
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
9968
#endif
9969
9970
    // Clipping test
9971
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
9972
    //const bool is_clipped = IsClippedEx(bb, id);
9973
    //if (is_clipped)
9974
    //    return false;
9975
60.6k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
9976
60.6k
    if (!is_rect_visible)
9977
4.43k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId))
9978
4.43k
            if (!g.LogEnabled)
9979
4.43k
                return false;
9980
9981
    // [DEBUG]
9982
56.1k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9983
56.1k
    if (id != 0 && id == g.DebugLocateId)
9984
0
        DebugLocateItemResolveWithLastItem();
9985
56.1k
#endif
9986
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
9987
9988
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
9989
56.1k
    if (is_rect_visible)
9990
56.1k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
9991
56.1k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
9992
2.09k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
9993
56.1k
    return true;
9994
60.6k
}
9995
9996
// Gets back to previous line and continue with horizontal layout
9997
//      offset_from_start_x == 0 : follow right after previous item
9998
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
9999
//      spacing_w < 0            : use default spacing if pos_x == 0, no spacing if pos_x != 0
10000
//      spacing_w >= 0           : enforce spacing amount
10001
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10002
0
{
10003
0
    ImGuiContext& g = *GImGui;
10004
0
    ImGuiWindow* window = g.CurrentWindow;
10005
0
    if (window->SkipItems)
10006
0
        return;
10007
10008
0
    if (offset_from_start_x != 0.0f)
10009
0
    {
10010
0
        if (spacing_w < 0.0f)
10011
0
            spacing_w = 0.0f;
10012
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10013
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10014
0
    }
10015
0
    else
10016
0
    {
10017
0
        if (spacing_w < 0.0f)
10018
0
            spacing_w = g.Style.ItemSpacing.x;
10019
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10020
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10021
0
    }
10022
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
10023
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10024
0
    window->DC.IsSameLine = true;
10025
0
}
10026
10027
ImVec2 ImGui::GetCursorScreenPos()
10028
4.94k
{
10029
4.94k
    ImGuiWindow* window = GetCurrentWindowRead();
10030
4.94k
    return window->DC.CursorPos;
10031
4.94k
}
10032
10033
// 2022/08/05: Setting cursor position also extend boundaries (via modifying CursorMaxPos) used to compute window size, group size etc.
10034
// I believe this was is a judicious choice but it's probably being relied upon (it has been the case since 1.31 and 1.50)
10035
// It would be sane if we requested user to use SetCursorPos() + Dummy(ImVec2(0,0)) to extend CursorMaxPos...
10036
void ImGui::SetCursorScreenPos(const ImVec2& pos)
10037
0
{
10038
0
    ImGuiWindow* window = GetCurrentWindow();
10039
0
    window->DC.CursorPos = pos;
10040
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10041
0
    window->DC.IsSetPos = true;
10042
0
}
10043
10044
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10045
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10046
ImVec2 ImGui::GetCursorPos()
10047
0
{
10048
0
    ImGuiWindow* window = GetCurrentWindowRead();
10049
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
10050
0
}
10051
10052
float ImGui::GetCursorPosX()
10053
0
{
10054
0
    ImGuiWindow* window = GetCurrentWindowRead();
10055
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10056
0
}
10057
10058
float ImGui::GetCursorPosY()
10059
0
{
10060
0
    ImGuiWindow* window = GetCurrentWindowRead();
10061
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10062
0
}
10063
10064
void ImGui::SetCursorPos(const ImVec2& local_pos)
10065
0
{
10066
0
    ImGuiWindow* window = GetCurrentWindow();
10067
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10068
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10069
0
    window->DC.IsSetPos = true;
10070
0
}
10071
10072
void ImGui::SetCursorPosX(float x)
10073
0
{
10074
0
    ImGuiWindow* window = GetCurrentWindow();
10075
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10076
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10077
0
    window->DC.IsSetPos = true;
10078
0
}
10079
10080
void ImGui::SetCursorPosY(float y)
10081
0
{
10082
0
    ImGuiWindow* window = GetCurrentWindow();
10083
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10084
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10085
0
    window->DC.IsSetPos = true;
10086
0
}
10087
10088
ImVec2 ImGui::GetCursorStartPos()
10089
0
{
10090
0
    ImGuiWindow* window = GetCurrentWindowRead();
10091
0
    return window->DC.CursorStartPos - window->Pos;
10092
0
}
10093
10094
void ImGui::Indent(float indent_w)
10095
0
{
10096
0
    ImGuiContext& g = *GImGui;
10097
0
    ImGuiWindow* window = GetCurrentWindow();
10098
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10099
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10100
0
}
10101
10102
void ImGui::Unindent(float indent_w)
10103
0
{
10104
0
    ImGuiContext& g = *GImGui;
10105
0
    ImGuiWindow* window = GetCurrentWindow();
10106
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10107
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10108
0
}
10109
10110
// Affect large frame+labels widgets only.
10111
void ImGui::SetNextItemWidth(float item_width)
10112
0
{
10113
0
    ImGuiContext& g = *GImGui;
10114
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10115
0
    g.NextItemData.Width = item_width;
10116
0
}
10117
10118
// FIXME: Remove the == 0.0f behavior?
10119
void ImGui::PushItemWidth(float item_width)
10120
0
{
10121
0
    ImGuiContext& g = *GImGui;
10122
0
    ImGuiWindow* window = g.CurrentWindow;
10123
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10124
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10125
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10126
0
}
10127
10128
void ImGui::PushMultiItemsWidths(int components, float w_full)
10129
0
{
10130
0
    ImGuiContext& g = *GImGui;
10131
0
    ImGuiWindow* window = g.CurrentWindow;
10132
0
    const ImGuiStyle& style = g.Style;
10133
0
    const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
10134
0
    const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
10135
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10136
0
    window->DC.ItemWidthStack.push_back(w_item_last);
10137
0
    for (int i = 0; i < components - 2; i++)
10138
0
        window->DC.ItemWidthStack.push_back(w_item_one);
10139
0
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
10140
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10141
0
}
10142
10143
void ImGui::PopItemWidth()
10144
0
{
10145
0
    ImGuiWindow* window = GetCurrentWindow();
10146
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10147
0
    window->DC.ItemWidthStack.pop_back();
10148
0
}
10149
10150
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10151
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10152
float ImGui::CalcItemWidth()
10153
0
{
10154
0
    ImGuiContext& g = *GImGui;
10155
0
    ImGuiWindow* window = g.CurrentWindow;
10156
0
    float w;
10157
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10158
0
        w = g.NextItemData.Width;
10159
0
    else
10160
0
        w = window->DC.ItemWidth;
10161
0
    if (w < 0.0f)
10162
0
    {
10163
0
        float region_max_x = GetContentRegionMaxAbs().x;
10164
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10165
0
    }
10166
0
    w = IM_FLOOR(w);
10167
0
    return w;
10168
0
}
10169
10170
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10171
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10172
// Note that only CalcItemWidth() is publicly exposed.
10173
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10174
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10175
0
{
10176
0
    ImGuiContext& g = *GImGui;
10177
0
    ImGuiWindow* window = g.CurrentWindow;
10178
10179
0
    ImVec2 region_max;
10180
0
    if (size.x < 0.0f || size.y < 0.0f)
10181
0
        region_max = GetContentRegionMaxAbs();
10182
10183
0
    if (size.x == 0.0f)
10184
0
        size.x = default_w;
10185
0
    else if (size.x < 0.0f)
10186
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10187
10188
0
    if (size.y == 0.0f)
10189
0
        size.y = default_h;
10190
0
    else if (size.y < 0.0f)
10191
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10192
10193
0
    return size;
10194
0
}
10195
10196
float ImGui::GetTextLineHeight()
10197
0
{
10198
0
    ImGuiContext& g = *GImGui;
10199
0
    return g.FontSize;
10200
0
}
10201
10202
float ImGui::GetTextLineHeightWithSpacing()
10203
4.22k
{
10204
4.22k
    ImGuiContext& g = *GImGui;
10205
4.22k
    return g.FontSize + g.Style.ItemSpacing.y;
10206
4.22k
}
10207
10208
float ImGui::GetFrameHeight()
10209
2
{
10210
2
    ImGuiContext& g = *GImGui;
10211
2
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10212
2
}
10213
10214
float ImGui::GetFrameHeightWithSpacing()
10215
0
{
10216
0
    ImGuiContext& g = *GImGui;
10217
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10218
0
}
10219
10220
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10221
10222
// FIXME: This is in window space (not screen space!).
10223
ImVec2 ImGui::GetContentRegionMax()
10224
0
{
10225
0
    ImGuiContext& g = *GImGui;
10226
0
    ImGuiWindow* window = g.CurrentWindow;
10227
0
    ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
10228
0
    if (window->DC.CurrentColumns || g.CurrentTable)
10229
0
        mx.x = window->WorkRect.Max.x - window->Pos.x;
10230
0
    return mx;
10231
0
}
10232
10233
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10234
ImVec2 ImGui::GetContentRegionMaxAbs()
10235
4.22k
{
10236
4.22k
    ImGuiContext& g = *GImGui;
10237
4.22k
    ImGuiWindow* window = g.CurrentWindow;
10238
4.22k
    ImVec2 mx = window->ContentRegionRect.Max;
10239
4.22k
    if (window->DC.CurrentColumns || g.CurrentTable)
10240
0
        mx.x = window->WorkRect.Max.x;
10241
4.22k
    return mx;
10242
4.22k
}
10243
10244
ImVec2 ImGui::GetContentRegionAvail()
10245
4.22k
{
10246
4.22k
    ImGuiWindow* window = GImGui->CurrentWindow;
10247
4.22k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10248
4.22k
}
10249
10250
// In window space (not screen space!)
10251
ImVec2 ImGui::GetWindowContentRegionMin()
10252
0
{
10253
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10254
0
    return window->ContentRegionRect.Min - window->Pos;
10255
0
}
10256
10257
ImVec2 ImGui::GetWindowContentRegionMax()
10258
4.22k
{
10259
4.22k
    ImGuiWindow* window = GImGui->CurrentWindow;
10260
4.22k
    return window->ContentRegionRect.Max - window->Pos;
10261
4.22k
}
10262
10263
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10264
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10265
// FIXME-OPT: Could we safely early out on ->SkipItems?
10266
void ImGui::BeginGroup()
10267
0
{
10268
0
    ImGuiContext& g = *GImGui;
10269
0
    ImGuiWindow* window = g.CurrentWindow;
10270
10271
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10272
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10273
0
    group_data.WindowID = window->ID;
10274
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10275
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10276
0
    group_data.BackupIndent = window->DC.Indent;
10277
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10278
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10279
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10280
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10281
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10282
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10283
0
    group_data.EmitItem = true;
10284
10285
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10286
0
    window->DC.Indent = window->DC.GroupOffset;
10287
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10288
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10289
0
    if (g.LogEnabled)
10290
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10291
0
}
10292
10293
void ImGui::EndGroup()
10294
0
{
10295
0
    ImGuiContext& g = *GImGui;
10296
0
    ImGuiWindow* window = g.CurrentWindow;
10297
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10298
10299
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10300
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10301
10302
0
    if (window->DC.IsSetPos)
10303
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10304
10305
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10306
10307
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10308
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10309
0
    window->DC.Indent = group_data.BackupIndent;
10310
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10311
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10312
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10313
0
    if (g.LogEnabled)
10314
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10315
10316
0
    if (!group_data.EmitItem)
10317
0
    {
10318
0
        g.GroupStack.pop_back();
10319
0
        return;
10320
0
    }
10321
10322
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10323
0
    ItemSize(group_bb.GetSize());
10324
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10325
10326
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10327
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10328
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10329
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10330
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10331
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10332
0
    if (group_contains_curr_active_id)
10333
0
        g.LastItemData.ID = g.ActiveId;
10334
0
    else if (group_contains_prev_active_id)
10335
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10336
0
    g.LastItemData.Rect = group_bb;
10337
10338
    // Forward Hovered flag
10339
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10340
0
    if (group_contains_curr_hovered_id)
10341
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10342
10343
    // Forward Edited flag
10344
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10345
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10346
10347
    // Forward Deactivated flag
10348
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10349
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10350
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10351
10352
0
    g.GroupStack.pop_back();
10353
    //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10354
0
}
10355
10356
10357
//-----------------------------------------------------------------------------
10358
// [SECTION] SCROLLING
10359
//-----------------------------------------------------------------------------
10360
10361
// Helper to snap on edges when aiming at an item very close to the edge,
10362
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10363
// When we refactor the scrolling API this may be configurable with a flag?
10364
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10365
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10366
0
{
10367
0
    if (target <= snap_min + snap_threshold)
10368
0
        return ImLerp(snap_min, target, center_ratio);
10369
0
    if (target >= snap_max - snap_threshold)
10370
0
        return ImLerp(target, snap_max, center_ratio);
10371
0
    return target;
10372
0
}
10373
10374
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10375
46.9k
{
10376
46.9k
    ImVec2 scroll = window->Scroll;
10377
46.9k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10378
140k
    for (int axis = 0; axis < 2; axis++)
10379
93.9k
    {
10380
93.9k
        if (window->ScrollTarget[axis] < FLT_MAX)
10381
4.81k
        {
10382
4.81k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10383
4.81k
            float scroll_target = window->ScrollTarget[axis];
10384
4.81k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10385
0
            {
10386
0
                float snap_min = 0.0f;
10387
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10388
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10389
0
            }
10390
4.81k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10391
4.81k
        }
10392
93.9k
        scroll[axis] = IM_FLOOR(ImMax(scroll[axis], 0.0f));
10393
93.9k
        if (!window->Collapsed && !window->SkipItems)
10394
59.6k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10395
93.9k
    }
10396
46.9k
    return scroll;
10397
46.9k
}
10398
10399
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10400
0
{
10401
0
    ImGuiContext& g = *GImGui;
10402
0
    ImGuiWindow* window = g.CurrentWindow;
10403
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10404
0
}
10405
10406
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10407
0
{
10408
0
    ScrollToRectEx(window, item_rect, flags);
10409
0
}
10410
10411
// Scroll to keep newly navigated item fully into view
10412
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10413
1
{
10414
1
    ImGuiContext& g = *GImGui;
10415
1
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10416
1
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10417
1
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10418
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10419
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10420
10421
    // Check that only one behavior is selected per axis
10422
1
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10423
1
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10424
10425
    // Defaults
10426
1
    ImGuiScrollFlags in_flags = flags;
10427
1
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10428
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10429
1
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10430
0
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10431
10432
1
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10433
1
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10434
1
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10435
1
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10436
10437
1
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10438
0
    {
10439
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10440
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10441
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10442
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10443
0
    }
10444
1
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10445
0
    {
10446
0
        if (can_be_fully_visible_x)
10447
0
            SetScrollFromPosX(window, ImFloor((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10448
0
        else
10449
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10450
0
    }
10451
10452
1
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10453
0
    {
10454
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10455
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10456
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10457
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10458
0
    }
10459
1
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10460
0
    {
10461
0
        if (can_be_fully_visible_y)
10462
0
            SetScrollFromPosY(window, ImFloor((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10463
0
        else
10464
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10465
0
    }
10466
10467
1
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10468
1
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10469
10470
    // Also scroll parent window to keep us into view if necessary
10471
1
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10472
0
    {
10473
        // FIXME-SCROLL: May be an option?
10474
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10475
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10476
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10477
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10478
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10479
0
    }
10480
10481
1
    return delta_scroll;
10482
1
}
10483
10484
float ImGui::GetScrollX()
10485
6.79k
{
10486
6.79k
    ImGuiWindow* window = GImGui->CurrentWindow;
10487
6.79k
    return window->Scroll.x;
10488
6.79k
}
10489
10490
float ImGui::GetScrollY()
10491
6.79k
{
10492
6.79k
    ImGuiWindow* window = GImGui->CurrentWindow;
10493
6.79k
    return window->Scroll.y;
10494
6.79k
}
10495
10496
float ImGui::GetScrollMaxX()
10497
0
{
10498
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10499
0
    return window->ScrollMax.x;
10500
0
}
10501
10502
float ImGui::GetScrollMaxY()
10503
0
{
10504
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10505
0
    return window->ScrollMax.y;
10506
0
}
10507
10508
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10509
2.54k
{
10510
2.54k
    window->ScrollTarget.x = scroll_x;
10511
2.54k
    window->ScrollTargetCenterRatio.x = 0.0f;
10512
2.54k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10513
2.54k
}
10514
10515
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10516
2.29k
{
10517
2.29k
    window->ScrollTarget.y = scroll_y;
10518
2.29k
    window->ScrollTargetCenterRatio.y = 0.0f;
10519
2.29k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10520
2.29k
}
10521
10522
void ImGui::SetScrollX(float scroll_x)
10523
2.53k
{
10524
2.53k
    ImGuiContext& g = *GImGui;
10525
2.53k
    SetScrollX(g.CurrentWindow, scroll_x);
10526
2.53k
}
10527
10528
void ImGui::SetScrollY(float scroll_y)
10529
2.27k
{
10530
2.27k
    ImGuiContext& g = *GImGui;
10531
2.27k
    SetScrollY(g.CurrentWindow, scroll_y);
10532
2.27k
}
10533
10534
// Note that a local position will vary depending on initial scroll value,
10535
// This is a little bit confusing so bear with us:
10536
//  - local_pos = (absolution_pos - window->Pos)
10537
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10538
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10539
//  - They mostly exist because of legacy API.
10540
// Following the rules above, when trying to work with scrolling code, consider that:
10541
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10542
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10543
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10544
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10545
0
{
10546
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10547
0
    window->ScrollTarget.x = IM_FLOOR(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10548
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10549
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10550
0
}
10551
10552
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10553
0
{
10554
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10555
0
    window->ScrollTarget.y = IM_FLOOR(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10556
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10557
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10558
0
}
10559
10560
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10561
0
{
10562
0
    ImGuiContext& g = *GImGui;
10563
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10564
0
}
10565
10566
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10567
0
{
10568
0
    ImGuiContext& g = *GImGui;
10569
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10570
0
}
10571
10572
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10573
void ImGui::SetScrollHereX(float center_x_ratio)
10574
0
{
10575
0
    ImGuiContext& g = *GImGui;
10576
0
    ImGuiWindow* window = g.CurrentWindow;
10577
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10578
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10579
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10580
10581
    // Tweak: snap on edges when aiming at an item very close to the edge
10582
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10583
0
}
10584
10585
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10586
void ImGui::SetScrollHereY(float center_y_ratio)
10587
0
{
10588
0
    ImGuiContext& g = *GImGui;
10589
0
    ImGuiWindow* window = g.CurrentWindow;
10590
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10591
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10592
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10593
10594
    // Tweak: snap on edges when aiming at an item very close to the edge
10595
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10596
0
}
10597
10598
//-----------------------------------------------------------------------------
10599
// [SECTION] TOOLTIPS
10600
//-----------------------------------------------------------------------------
10601
10602
bool ImGui::BeginTooltip()
10603
15
{
10604
15
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10605
15
}
10606
10607
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10608
15
{
10609
15
    ImGuiContext& g = *GImGui;
10610
10611
15
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
10612
0
    {
10613
        // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
10614
        // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
10615
        // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
10616
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10617
0
        ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
10618
0
        SetNextWindowPos(tooltip_pos);
10619
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
10620
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
10621
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
10622
0
    }
10623
10624
15
    char window_name[16];
10625
15
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
10626
15
    if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
10627
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
10628
0
            if (window->Active)
10629
0
            {
10630
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
10631
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(window);
10632
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
10633
0
            }
10634
15
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
10635
15
    Begin(window_name, NULL, flags | extra_window_flags);
10636
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
10637
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
10638
    //if (!ret)
10639
    //    End();
10640
    //return ret;
10641
15
    return true;
10642
15
}
10643
10644
void ImGui::EndTooltip()
10645
15
{
10646
15
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
10647
15
    End();
10648
15
}
10649
10650
void ImGui::SetTooltipV(const char* fmt, va_list args)
10651
0
{
10652
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None))
10653
0
        return;
10654
0
    TextV(fmt, args);
10655
0
    EndTooltip();
10656
0
}
10657
10658
void ImGui::SetTooltip(const char* fmt, ...)
10659
0
{
10660
0
    va_list args;
10661
0
    va_start(args, fmt);
10662
0
    SetTooltipV(fmt, args);
10663
0
    va_end(args);
10664
0
}
10665
10666
//-----------------------------------------------------------------------------
10667
// [SECTION] POPUPS
10668
//-----------------------------------------------------------------------------
10669
10670
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
10671
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
10672
0
{
10673
0
    ImGuiContext& g = *GImGui;
10674
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
10675
0
    {
10676
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
10677
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
10678
0
        IM_ASSERT(id == 0);
10679
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10680
0
            return g.OpenPopupStack.Size > 0;
10681
0
        else
10682
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
10683
0
    }
10684
0
    else
10685
0
    {
10686
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10687
0
        {
10688
            // Return true if the popup is open anywhere in the popup stack
10689
0
            for (int n = 0; n < g.OpenPopupStack.Size; n++)
10690
0
                if (g.OpenPopupStack[n].PopupId == id)
10691
0
                    return true;
10692
0
            return false;
10693
0
        }
10694
0
        else
10695
0
        {
10696
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
10697
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
10698
0
        }
10699
0
    }
10700
0
}
10701
10702
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
10703
0
{
10704
0
    ImGuiContext& g = *GImGui;
10705
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
10706
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
10707
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
10708
0
    return IsPopupOpen(id, popup_flags);
10709
0
}
10710
10711
ImGuiWindow* ImGui::GetTopMostPopupModal()
10712
64.1k
{
10713
64.1k
    ImGuiContext& g = *GImGui;
10714
64.1k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10715
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10716
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
10717
0
                return popup;
10718
64.1k
    return NULL;
10719
64.1k
}
10720
10721
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
10722
21.3k
{
10723
21.3k
    ImGuiContext& g = *GImGui;
10724
21.3k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10725
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10726
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
10727
0
                return popup;
10728
21.3k
    return NULL;
10729
21.3k
}
10730
10731
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
10732
0
{
10733
0
    ImGuiContext& g = *GImGui;
10734
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10735
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
10736
0
    OpenPopupEx(id, popup_flags);
10737
0
}
10738
10739
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
10740
0
{
10741
0
    OpenPopupEx(id, popup_flags);
10742
0
}
10743
10744
// Mark popup as open (toggle toward open state).
10745
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
10746
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
10747
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
10748
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
10749
0
{
10750
0
    ImGuiContext& g = *GImGui;
10751
0
    ImGuiWindow* parent_window = g.CurrentWindow;
10752
0
    const int current_stack_size = g.BeginPopupStack.Size;
10753
10754
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
10755
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
10756
0
            return;
10757
10758
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
10759
0
    popup_ref.PopupId = id;
10760
0
    popup_ref.Window = NULL;
10761
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
10762
0
    popup_ref.OpenFrameCount = g.FrameCount;
10763
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
10764
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
10765
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
10766
10767
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
10768
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
10769
0
    {
10770
0
        g.OpenPopupStack.push_back(popup_ref);
10771
0
    }
10772
0
    else
10773
0
    {
10774
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
10775
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
10776
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
10777
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
10778
0
        {
10779
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
10780
0
        }
10781
0
        else
10782
0
        {
10783
            // Close child popups if any, then flag popup for open/reopen
10784
0
            ClosePopupToLevel(current_stack_size, false);
10785
0
            g.OpenPopupStack.push_back(popup_ref);
10786
0
        }
10787
10788
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
10789
        // This is equivalent to what ClosePopupToLevel() does.
10790
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
10791
        //    FocusWindow(parent_window);
10792
0
    }
10793
0
}
10794
10795
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
10796
// This function closes any popups that are over 'ref_window'.
10797
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
10798
2.47k
{
10799
2.47k
    ImGuiContext& g = *GImGui;
10800
2.47k
    if (g.OpenPopupStack.Size == 0)
10801
2.47k
        return;
10802
10803
    // Don't close our own child popup windows.
10804
0
    int popup_count_to_keep = 0;
10805
0
    if (ref_window)
10806
0
    {
10807
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
10808
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
10809
0
        {
10810
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
10811
0
            if (!popup.Window)
10812
0
                continue;
10813
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
10814
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
10815
0
                continue;
10816
10817
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
10818
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
10819
            //     Window -> Popup1 -> Popup2 -> Popup3
10820
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
10821
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
10822
0
            bool ref_window_is_descendent_of_popup = false;
10823
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
10824
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
10825
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
10826
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
10827
0
                    {
10828
0
                        ref_window_is_descendent_of_popup = true;
10829
0
                        break;
10830
0
                    }
10831
0
            if (!ref_window_is_descendent_of_popup)
10832
0
                break;
10833
0
        }
10834
0
    }
10835
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10836
0
    {
10837
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
10838
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
10839
0
    }
10840
0
}
10841
10842
void ImGui::ClosePopupsExceptModals()
10843
0
{
10844
0
    ImGuiContext& g = *GImGui;
10845
10846
0
    int popup_count_to_keep;
10847
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
10848
0
    {
10849
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
10850
0
        if (!window || window->Flags & ImGuiWindowFlags_Modal)
10851
0
            break;
10852
0
    }
10853
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10854
0
        ClosePopupToLevel(popup_count_to_keep, true);
10855
0
}
10856
10857
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
10858
0
{
10859
0
    ImGuiContext& g = *GImGui;
10860
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
10861
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
10862
10863
    // Trim open popup stack
10864
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
10865
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
10866
0
    g.OpenPopupStack.resize(remaining);
10867
10868
0
    if (restore_focus_to_window_under_popup)
10869
0
    {
10870
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
10871
0
        if (focus_window && !focus_window->WasActive && popup_window)
10872
0
        {
10873
            // Fallback
10874
0
            FocusTopMostWindowUnderOne(popup_window, NULL);
10875
0
        }
10876
0
        else
10877
0
        {
10878
0
            if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
10879
0
                focus_window = NavRestoreLastChildNavWindow(focus_window);
10880
0
            FocusWindow(focus_window);
10881
0
        }
10882
0
    }
10883
0
}
10884
10885
// Close the popup we have begin-ed into.
10886
void ImGui::CloseCurrentPopup()
10887
0
{
10888
0
    ImGuiContext& g = *GImGui;
10889
0
    int popup_idx = g.BeginPopupStack.Size - 1;
10890
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
10891
0
        return;
10892
10893
    // Closing a menu closes its top-most parent popup (unless a modal)
10894
0
    while (popup_idx > 0)
10895
0
    {
10896
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
10897
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
10898
0
        bool close_parent = false;
10899
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
10900
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
10901
0
                close_parent = true;
10902
0
        if (!close_parent)
10903
0
            break;
10904
0
        popup_idx--;
10905
0
    }
10906
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
10907
0
    ClosePopupToLevel(popup_idx, true);
10908
10909
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
10910
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
10911
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
10912
0
    if (ImGuiWindow* window = g.NavWindow)
10913
0
        window->DC.NavHideHighlightOneFrame = true;
10914
0
}
10915
10916
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
10917
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
10918
0
{
10919
0
    ImGuiContext& g = *GImGui;
10920
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10921
0
    {
10922
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10923
0
        return false;
10924
0
    }
10925
10926
0
    char name[20];
10927
0
    if (flags & ImGuiWindowFlags_ChildMenu)
10928
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
10929
0
    else
10930
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
10931
10932
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
10933
0
    bool is_open = Begin(name, NULL, flags);
10934
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
10935
0
        EndPopup();
10936
10937
0
    return is_open;
10938
0
}
10939
10940
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
10941
0
{
10942
0
    ImGuiContext& g = *GImGui;
10943
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
10944
0
    {
10945
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10946
0
        return false;
10947
0
    }
10948
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
10949
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10950
0
    return BeginPopupEx(id, flags);
10951
0
}
10952
10953
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
10954
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
10955
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
10956
0
{
10957
0
    ImGuiContext& g = *GImGui;
10958
0
    ImGuiWindow* window = g.CurrentWindow;
10959
0
    const ImGuiID id = window->GetID(name);
10960
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10961
0
    {
10962
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10963
0
        return false;
10964
0
    }
10965
10966
    // Center modal windows by default for increased visibility
10967
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
10968
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
10969
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
10970
0
    {
10971
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
10972
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
10973
0
    }
10974
10975
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
10976
0
    const bool is_open = Begin(name, p_open, flags);
10977
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
10978
0
    {
10979
0
        EndPopup();
10980
0
        if (is_open)
10981
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
10982
0
        return false;
10983
0
    }
10984
0
    return is_open;
10985
0
}
10986
10987
void ImGui::EndPopup()
10988
0
{
10989
0
    ImGuiContext& g = *GImGui;
10990
0
    ImGuiWindow* window = g.CurrentWindow;
10991
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
10992
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
10993
10994
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
10995
0
    if (g.NavWindow == window)
10996
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
10997
10998
    // Child-popups don't need to be laid out
10999
0
    IM_ASSERT(g.WithinEndChild == false);
11000
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
11001
0
        g.WithinEndChild = true;
11002
0
    End();
11003
0
    g.WithinEndChild = false;
11004
0
}
11005
11006
// Helper to open a popup if mouse button is released over the item
11007
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11008
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11009
0
{
11010
0
    ImGuiContext& g = *GImGui;
11011
0
    ImGuiWindow* window = g.CurrentWindow;
11012
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11013
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11014
0
    {
11015
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11016
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11017
0
        OpenPopupEx(id, popup_flags);
11018
0
    }
11019
0
}
11020
11021
// This is a helper to handle the simplest case of associating one named popup to one given widget.
11022
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11023
// - To create a popup with a specific identifier, pass it in str_id.
11024
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11025
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11026
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11027
//   This is essentially the same as:
11028
//       id = str_id ? GetID(str_id) : GetItemID();
11029
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11030
//       return BeginPopup(id);
11031
//   Which is essentially the same as:
11032
//       id = str_id ? GetID(str_id) : GetItemID();
11033
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11034
//           OpenPopup(id);
11035
//       return BeginPopup(id);
11036
//   The main difference being that this is tweaked to avoid computing the ID twice.
11037
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11038
0
{
11039
0
    ImGuiContext& g = *GImGui;
11040
0
    ImGuiWindow* window = g.CurrentWindow;
11041
0
    if (window->SkipItems)
11042
0
        return false;
11043
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11044
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11045
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11046
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11047
0
        OpenPopupEx(id, popup_flags);
11048
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11049
0
}
11050
11051
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11052
0
{
11053
0
    ImGuiContext& g = *GImGui;
11054
0
    ImGuiWindow* window = g.CurrentWindow;
11055
0
    if (!str_id)
11056
0
        str_id = "window_context";
11057
0
    ImGuiID id = window->GetID(str_id);
11058
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11059
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11060
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11061
0
            OpenPopupEx(id, popup_flags);
11062
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11063
0
}
11064
11065
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11066
0
{
11067
0
    ImGuiContext& g = *GImGui;
11068
0
    ImGuiWindow* window = g.CurrentWindow;
11069
0
    if (!str_id)
11070
0
        str_id = "void_context";
11071
0
    ImGuiID id = window->GetID(str_id);
11072
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11073
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11074
0
        if (GetTopMostPopupModal() == NULL)
11075
0
            OpenPopupEx(id, popup_flags);
11076
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11077
0
}
11078
11079
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11080
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11081
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11082
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11083
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
11084
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11085
15
{
11086
15
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11087
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11088
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11089
11090
    // Combo Box policy (we want a connecting edge)
11091
15
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
11092
0
    {
11093
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11094
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11095
0
        {
11096
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11097
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11098
0
                continue;
11099
0
            ImVec2 pos;
11100
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11101
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11102
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11103
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11104
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11105
0
                continue;
11106
0
            *last_dir = dir;
11107
0
            return pos;
11108
0
        }
11109
0
    }
11110
11111
    // Tooltip and Default popup policy
11112
    // (Always first try the direction we used on the last frame, if any)
11113
15
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11114
15
    {
11115
15
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11116
15
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11117
15
        {
11118
15
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11119
15
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11120
0
                continue;
11121
11122
15
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11123
15
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11124
11125
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11126
15
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11127
0
                continue;
11128
15
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11129
0
                continue;
11130
11131
15
            ImVec2 pos;
11132
15
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11133
15
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11134
11135
            // Clamp top-left corner of popup
11136
15
            pos.x = ImMax(pos.x, r_outer.Min.x);
11137
15
            pos.y = ImMax(pos.y, r_outer.Min.y);
11138
11139
15
            *last_dir = dir;
11140
15
            return pos;
11141
15
        }
11142
15
    }
11143
11144
    // Fallback when not enough room:
11145
0
    *last_dir = ImGuiDir_None;
11146
11147
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11148
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11149
0
        return ref_pos + ImVec2(2, 2);
11150
11151
    // Otherwise try to keep within display
11152
0
    ImVec2 pos = ref_pos;
11153
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11154
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11155
0
    return pos;
11156
0
}
11157
11158
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11159
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11160
15
{
11161
15
    ImGuiContext& g = *GImGui;
11162
15
    ImRect r_screen;
11163
15
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11164
0
    {
11165
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11166
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11167
0
        r_screen.Min = monitor.WorkPos;
11168
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11169
0
    }
11170
15
    else
11171
15
    {
11172
        // Use the full viewport area (not work area) for popups
11173
15
        r_screen = window->Viewport->GetMainRect();
11174
15
    }
11175
15
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11176
15
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11177
15
    return r_screen;
11178
15
}
11179
11180
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11181
15
{
11182
15
    ImGuiContext& g = *GImGui;
11183
11184
15
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11185
15
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11186
0
    {
11187
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11188
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11189
0
        ImGuiWindow* parent_window = window->ParentWindow;
11190
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11191
0
        ImRect r_avoid;
11192
0
        if (parent_window->DC.MenuBarAppending)
11193
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11194
0
        else
11195
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11196
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11197
0
    }
11198
15
    if (window->Flags & ImGuiWindowFlags_Popup)
11199
0
    {
11200
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11201
0
    }
11202
15
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11203
15
    {
11204
        // Position tooltip (always follows mouse)
11205
15
        float sc = g.Style.MouseCursorScale;
11206
15
        ImVec2 ref_pos = NavCalcPreferredRefPos();
11207
15
        ImRect r_avoid;
11208
15
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11209
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11210
15
        else
11211
15
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11212
15
        return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11213
15
    }
11214
0
    IM_ASSERT(0);
11215
0
    return window->Pos;
11216
15
}
11217
11218
//-----------------------------------------------------------------------------
11219
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11220
//-----------------------------------------------------------------------------
11221
11222
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11223
// In our terminology those should be interchangeable, yet right now this is super confusing.
11224
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11225
11226
void ImGui::SetNavWindow(ImGuiWindow* window)
11227
2.47k
{
11228
2.47k
    ImGuiContext& g = *GImGui;
11229
2.47k
    if (g.NavWindow != window)
11230
2.47k
    {
11231
2.47k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11232
2.47k
        g.NavWindow = window;
11233
2.47k
    }
11234
2.47k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11235
2.47k
    NavUpdateAnyRequestFlag();
11236
2.47k
}
11237
11238
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11239
62
{
11240
62
    ImGuiContext& g = *GImGui;
11241
62
    IM_ASSERT(g.NavWindow != NULL);
11242
62
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11243
62
    g.NavId = id;
11244
62
    g.NavLayer = nav_layer;
11245
62
    g.NavFocusScopeId = focus_scope_id;
11246
62
    g.NavWindow->NavLastIds[nav_layer] = id;
11247
62
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11248
62
}
11249
11250
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11251
42
{
11252
42
    ImGuiContext& g = *GImGui;
11253
42
    IM_ASSERT(id != 0);
11254
11255
42
    if (g.NavWindow != window)
11256
42
       SetNavWindow(window);
11257
11258
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11259
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11260
42
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11261
42
    g.NavId = id;
11262
42
    g.NavLayer = nav_layer;
11263
42
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11264
42
    window->NavLastIds[nav_layer] = id;
11265
42
    if (g.LastItemData.ID == id)
11266
42
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11267
11268
42
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
11269
0
        g.NavDisableMouseHover = true;
11270
42
    else
11271
42
        g.NavDisableHighlight = true;
11272
42
}
11273
11274
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11275
0
{
11276
0
    if (ImFabs(dx) > ImFabs(dy))
11277
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11278
0
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11279
0
}
11280
11281
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
11282
0
{
11283
0
    if (a1 < b0)
11284
0
        return a1 - b0;
11285
0
    if (b1 < a0)
11286
0
        return a0 - b1;
11287
0
    return 0.0f;
11288
0
}
11289
11290
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
11291
0
{
11292
0
    if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11293
0
    {
11294
0
        r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
11295
0
        r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
11296
0
    }
11297
0
    else // FIXME: PageUp/PageDown are leaving move_dir == None
11298
0
    {
11299
0
        r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
11300
0
        r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
11301
0
    }
11302
0
}
11303
11304
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11305
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11306
51
{
11307
51
    ImGuiContext& g = *GImGui;
11308
51
    ImGuiWindow* window = g.CurrentWindow;
11309
51
    if (g.NavLayer != window->DC.NavLayerCurrent)
11310
51
        return false;
11311
11312
    // FIXME: Those are not good variables names
11313
0
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11314
0
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11315
0
    g.NavScoringDebugCount++;
11316
11317
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11318
0
    if (window->ParentWindow == g.NavWindow)
11319
0
    {
11320
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11321
0
        if (!window->ClipRect.Overlaps(cand))
11322
0
            return false;
11323
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11324
0
    }
11325
11326
    // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
11327
    // For example, this ensures that items in one column are not reached when moving vertically from items in another column.
11328
0
    NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
11329
11330
    // Compute distance between boxes
11331
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11332
0
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11333
0
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11334
0
    if (dby != 0.0f && dbx != 0.0f)
11335
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11336
0
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11337
11338
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11339
0
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11340
0
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11341
0
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11342
11343
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11344
0
    ImGuiDir quadrant;
11345
0
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11346
0
    if (dbx != 0.0f || dby != 0.0f)
11347
0
    {
11348
        // For non-overlapping boxes, use distance between boxes
11349
0
        dax = dbx;
11350
0
        day = dby;
11351
0
        dist_axial = dist_box;
11352
0
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11353
0
    }
11354
0
    else if (dcx != 0.0f || dcy != 0.0f)
11355
0
    {
11356
        // For overlapping boxes with different centers, use distance between centers
11357
0
        dax = dcx;
11358
0
        day = dcy;
11359
0
        dist_axial = dist_center;
11360
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11361
0
    }
11362
0
    else
11363
0
    {
11364
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11365
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11366
0
    }
11367
11368
#if IMGUI_DEBUG_NAV_SCORING
11369
    char buf[128];
11370
    if (IsMouseHoveringRect(cand.Min, cand.Max))
11371
    {
11372
        ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
11373
        ImDrawList* draw_list = GetForegroundDrawList(window);
11374
        draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
11375
        draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
11376
        draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
11377
        draw_list->AddText(cand.Max, ~0U, buf);
11378
    }
11379
    else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
11380
    {
11381
        if (quadrant == g.NavMoveDir)
11382
        {
11383
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11384
            ImDrawList* draw_list = GetForegroundDrawList(window);
11385
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
11386
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11387
        }
11388
    }
11389
#endif
11390
11391
    // Is it in the quadrant we're interested in moving to?
11392
0
    bool new_best = false;
11393
0
    const ImGuiDir move_dir = g.NavMoveDir;
11394
0
    if (quadrant == move_dir)
11395
0
    {
11396
        // Does it beat the current best candidate?
11397
0
        if (dist_box < result->DistBox)
11398
0
        {
11399
0
            result->DistBox = dist_box;
11400
0
            result->DistCenter = dist_center;
11401
0
            return true;
11402
0
        }
11403
0
        if (dist_box == result->DistBox)
11404
0
        {
11405
            // Try using distance between center points to break ties
11406
0
            if (dist_center < result->DistCenter)
11407
0
            {
11408
0
                result->DistCenter = dist_center;
11409
0
                new_best = true;
11410
0
            }
11411
0
            else if (dist_center == result->DistCenter)
11412
0
            {
11413
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11414
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11415
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11416
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11417
0
                    new_best = true;
11418
0
            }
11419
0
        }
11420
0
    }
11421
11422
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11423
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11424
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11425
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11426
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11427
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11428
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11429
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11430
0
            {
11431
0
                result->DistAxial = dist_axial;
11432
0
                new_best = true;
11433
0
            }
11434
11435
0
    return new_best;
11436
0
}
11437
11438
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11439
1
{
11440
1
    ImGuiContext& g = *GImGui;
11441
1
    ImGuiWindow* window = g.CurrentWindow;
11442
1
    result->Window = window;
11443
1
    result->ID = g.LastItemData.ID;
11444
1
    result->FocusScopeId = g.CurrentFocusScopeId;
11445
1
    result->InFlags = g.LastItemData.InFlags;
11446
1
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11447
1
}
11448
11449
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11450
// This is called after LastItemData is set.
11451
static void ImGui::NavProcessItem()
11452
101
{
11453
101
    ImGuiContext& g = *GImGui;
11454
101
    ImGuiWindow* window = g.CurrentWindow;
11455
101
    const ImGuiID id = g.LastItemData.ID;
11456
101
    const ImRect nav_bb = g.LastItemData.NavRect;
11457
101
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11458
11459
    // Process Init Request
11460
101
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11461
1
    {
11462
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11463
1
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11464
1
        if (candidate_for_nav_default_focus || g.NavInitResultId == 0)
11465
1
        {
11466
1
            g.NavInitResultId = id;
11467
1
            g.NavInitResultRectRel = WindowRectAbsToRel(window, nav_bb);
11468
1
        }
11469
1
        if (candidate_for_nav_default_focus)
11470
1
        {
11471
1
            g.NavInitRequest = false; // Found a match, clear request
11472
1
            NavUpdateAnyRequestFlag();
11473
1
        }
11474
1
    }
11475
11476
    // Process Move Request (scoring for navigation)
11477
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11478
101
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
11479
30
    {
11480
30
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;
11481
30
        if (is_tabbing)
11482
3
        {
11483
3
            NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
11484
3
        }
11485
27
        else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
11486
26
        {
11487
26
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11488
26
            if (NavScoreItem(result))
11489
0
                NavApplyItemToResult(result);
11490
11491
            // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11492
26
            const float VISIBLE_RATIO = 0.70f;
11493
26
            if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11494
25
                if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11495
25
                    if (NavScoreItem(&g.NavMoveResultLocalVisible))
11496
0
                        NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11497
26
        }
11498
30
    }
11499
11500
    // Update window-relative bounding box of navigated item
11501
101
    if (g.NavId == id)
11502
62
    {
11503
62
        if (g.NavWindow != window)
11504
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11505
62
        g.NavLayer = window->DC.NavLayerCurrent;
11506
62
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11507
62
        g.NavIdIsAlive = true;
11508
62
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb);    // Store item bounding box (relative to window position)
11509
62
    }
11510
101
}
11511
11512
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11513
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11514
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11515
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11516
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11517
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11518
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11519
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
11520
3
{
11521
3
    ImGuiContext& g = *GImGui;
11522
11523
3
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
11524
3
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
11525
2
            return;
11526
11527
    // - Can always land on an item when using API call.
11528
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
11529
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
11530
1
    bool can_stop;
11531
1
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
11532
0
        can_stop = true;
11533
1
    else
11534
1
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
11535
11536
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11537
1
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11538
1
    if (g.NavTabbingDir == +1)
11539
1
    {
11540
        // Tab Forward or SetKeyboardFocusHere() with >= 0
11541
1
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
11542
1
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11543
1
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
11544
0
            NavMoveRequestResolveWithLastItem(result);
11545
1
        else if (g.NavId == id)
11546
1
            g.NavTabbingCounter = 1;
11547
1
    }
11548
0
    else if (g.NavTabbingDir == -1)
11549
0
    {
11550
        // Tab Backward
11551
0
        if (g.NavId == id)
11552
0
        {
11553
0
            if (result->ID)
11554
0
            {
11555
0
                g.NavMoveScoringItems = false;
11556
0
                NavUpdateAnyRequestFlag();
11557
0
            }
11558
0
        }
11559
0
        else if (can_stop)
11560
0
        {
11561
            // Keep applying until reaching NavId
11562
0
            NavApplyItemToResult(result);
11563
0
        }
11564
0
    }
11565
0
    else if (g.NavTabbingDir == 0)
11566
0
    {
11567
0
        if (can_stop && g.NavId == id)
11568
0
            NavMoveRequestResolveWithLastItem(result);
11569
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
11570
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11571
0
    }
11572
1
}
11573
11574
bool ImGui::NavMoveRequestButNoResultYet()
11575
3.42k
{
11576
3.42k
    ImGuiContext& g = *GImGui;
11577
3.42k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
11578
3.42k
}
11579
11580
// FIXME: ScoringRect is not set
11581
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11582
40
{
11583
40
    ImGuiContext& g = *GImGui;
11584
40
    IM_ASSERT(g.NavWindow != NULL);
11585
11586
40
    if (move_flags & ImGuiNavMoveFlags_Tabbing)
11587
8
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
11588
11589
40
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
11590
40
    g.NavMoveDir = move_dir;
11591
40
    g.NavMoveDirForDebug = move_dir;
11592
40
    g.NavMoveClipDir = clip_dir;
11593
40
    g.NavMoveFlags = move_flags;
11594
40
    g.NavMoveScrollFlags = scroll_flags;
11595
40
    g.NavMoveForwardToNextFrame = false;
11596
40
    g.NavMoveKeyMods = g.IO.KeyMods;
11597
40
    g.NavMoveResultLocal.Clear();
11598
40
    g.NavMoveResultLocalVisible.Clear();
11599
40
    g.NavMoveResultOther.Clear();
11600
40
    g.NavTabbingCounter = 0;
11601
40
    g.NavTabbingResultFirst.Clear();
11602
40
    NavUpdateAnyRequestFlag();
11603
40
}
11604
11605
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
11606
0
{
11607
0
    ImGuiContext& g = *GImGui;
11608
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
11609
0
    NavApplyItemToResult(result);
11610
0
    NavUpdateAnyRequestFlag();
11611
0
}
11612
11613
void ImGui::NavMoveRequestCancel()
11614
9
{
11615
9
    ImGuiContext& g = *GImGui;
11616
9
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11617
9
    NavUpdateAnyRequestFlag();
11618
9
}
11619
11620
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
11621
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11622
0
{
11623
0
    ImGuiContext& g = *GImGui;
11624
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
11625
0
    NavMoveRequestCancel();
11626
0
    g.NavMoveForwardToNextFrame = true;
11627
0
    g.NavMoveDir = move_dir;
11628
0
    g.NavMoveClipDir = clip_dir;
11629
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
11630
0
    g.NavMoveScrollFlags = scroll_flags;
11631
0
}
11632
11633
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
11634
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
11635
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
11636
0
{
11637
0
    ImGuiContext& g = *GImGui;
11638
0
    IM_ASSERT(wrap_flags != 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
11639
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test
11640
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
11641
0
        g.NavMoveFlags |= wrap_flags;
11642
0
}
11643
11644
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
11645
// This way we could find the last focused window among our children. It would be much less confusing this way?
11646
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
11647
2.20k
{
11648
2.20k
    ImGuiWindow* parent = nav_window;
11649
4.13k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
11650
1.93k
        parent = parent->ParentWindow;
11651
2.20k
    if (parent && parent != nav_window)
11652
1.93k
        parent->NavLastChildNavWindow = nav_window;
11653
2.20k
}
11654
11655
// Restore the last focused child.
11656
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
11657
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
11658
28
{
11659
28
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
11660
9
        return window->NavLastChildNavWindow;
11661
19
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
11662
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
11663
0
            return tab->Window;
11664
19
    return window;
11665
19
}
11666
11667
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
11668
28
{
11669
28
    ImGuiContext& g = *GImGui;
11670
28
    if (layer == ImGuiNavLayer_Main)
11671
28
    {
11672
28
        ImGuiWindow* prev_nav_window = g.NavWindow;
11673
28
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
11674
28
        if (prev_nav_window)
11675
28
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
11676
28
    }
11677
28
    ImGuiWindow* window = g.NavWindow;
11678
28
    if (window->NavLastIds[layer] != 0)
11679
11
    {
11680
11
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
11681
11
    }
11682
17
    else
11683
17
    {
11684
17
        g.NavLayer = layer;
11685
17
        NavInitWindow(window, true);
11686
17
    }
11687
28
}
11688
11689
void ImGui::NavRestoreHighlightAfterMove()
11690
30
{
11691
30
    ImGuiContext& g = *GImGui;
11692
30
    g.NavDisableHighlight = false;
11693
30
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
11694
30
}
11695
11696
static inline void ImGui::NavUpdateAnyRequestFlag()
11697
23.9k
{
11698
23.9k
    ImGuiContext& g = *GImGui;
11699
23.9k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
11700
23.9k
    if (g.NavAnyRequest)
11701
23.9k
        IM_ASSERT(g.NavWindow != NULL);
11702
23.9k
}
11703
11704
// This needs to be called before we submit any widget (aka in or before Begin)
11705
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
11706
24
{
11707
    // FIXME: ChildWindow test here is wrong for docking
11708
24
    ImGuiContext& g = *GImGui;
11709
24
    IM_ASSERT(window == g.NavWindow);
11710
11711
24
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
11712
0
    {
11713
0
        g.NavId = 0;
11714
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11715
0
        return;
11716
0
    }
11717
11718
24
    bool init_for_nav = false;
11719
24
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
11720
24
        init_for_nav = true;
11721
24
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
11722
24
    if (init_for_nav)
11723
24
    {
11724
24
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
11725
24
        g.NavInitRequest = true;
11726
24
        g.NavInitRequestFromMove = false;
11727
24
        g.NavInitResultId = 0;
11728
24
        g.NavInitResultRectRel = ImRect();
11729
24
        NavUpdateAnyRequestFlag();
11730
24
    }
11731
0
    else
11732
0
    {
11733
0
        g.NavId = window->NavLastIds[0];
11734
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11735
0
    }
11736
24
}
11737
11738
static ImVec2 ImGui::NavCalcPreferredRefPos()
11739
15
{
11740
15
    ImGuiContext& g = *GImGui;
11741
15
    ImGuiWindow* window = g.NavWindow;
11742
15
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
11743
15
    {
11744
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
11745
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
11746
        // In theory we could move that +1.0f offset in OpenPopupEx()
11747
15
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
11748
15
        return ImVec2(p.x + 1.0f, p.y);
11749
15
    }
11750
0
    else
11751
0
    {
11752
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
11753
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
11754
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
11755
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
11756
0
        {
11757
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11758
0
            rect_rel.Translate(window->Scroll - next_scroll);
11759
0
        }
11760
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
11761
0
        ImGuiViewport* viewport = window->Viewport;
11762
0
        return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
11763
0
    }
11764
15
}
11765
11766
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
11767
0
{
11768
0
    ImGuiContext& g = *GImGui;
11769
0
    float repeat_delay, repeat_rate;
11770
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
11771
11772
0
    ImGuiKey key_less, key_more;
11773
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
11774
0
    {
11775
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
11776
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
11777
0
    }
11778
0
    else
11779
0
    {
11780
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
11781
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
11782
0
    }
11783
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
11784
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
11785
0
        amount = 0.0f;
11786
0
    return amount;
11787
0
}
11788
11789
static void ImGui::NavUpdate()
11790
21.3k
{
11791
21.3k
    ImGuiContext& g = *GImGui;
11792
21.3k
    ImGuiIO& io = g.IO;
11793
11794
21.3k
    io.WantSetMousePos = false;
11795
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
11796
11797
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
11798
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
11799
21.3k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11800
21.3k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
11801
21.3k
    if (nav_gamepad_active)
11802
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
11803
0
            if (IsKeyDown(key))
11804
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
11805
21.3k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11806
21.3k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
11807
21.3k
    if (nav_keyboard_active)
11808
21.3k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
11809
149k
            if (IsKeyDown(key))
11810
3.90k
                g.NavInputSource = ImGuiInputSource_Keyboard;
11811
11812
    // Process navigation init request (select first/default focus)
11813
21.3k
    if (g.NavInitResultId != 0)
11814
1
        NavInitRequestApplyResult();
11815
21.3k
    g.NavInitRequest = false;
11816
21.3k
    g.NavInitRequestFromMove = false;
11817
21.3k
    g.NavInitResultId = 0;
11818
21.3k
    g.NavJustMovedToId = 0;
11819
11820
    // Process navigation move request
11821
21.3k
    if (g.NavMoveSubmitted)
11822
30
        NavMoveRequestApplyResult();
11823
21.3k
    g.NavTabbingCounter = 0;
11824
21.3k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11825
11826
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
11827
21.3k
    bool set_mouse_pos = false;
11828
21.3k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
11829
11
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
11830
11
            set_mouse_pos = true;
11831
21.3k
    g.NavMousePosDirty = false;
11832
21.3k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
11833
11834
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
11835
21.3k
    if (g.NavWindow)
11836
2.20k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
11837
21.3k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
11838
16
        g.NavWindow->NavLastChildNavWindow = NULL;
11839
11840
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
11841
21.3k
    NavUpdateWindowing();
11842
11843
    // Set output flags for user application
11844
21.3k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
11845
21.3k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
11846
11847
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
11848
21.3k
    NavUpdateCancelRequest();
11849
11850
    // Process manual activation request
11851
21.3k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
11852
21.3k
    g.NavActivateFlags = ImGuiActivateFlags_None;
11853
21.3k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11854
60
    {
11855
60
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
11856
60
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
11857
60
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
11858
60
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
11859
60
        if (g.ActiveId == 0 && activate_pressed)
11860
4
        {
11861
4
            g.NavActivateId = g.NavId;
11862
4
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
11863
4
        }
11864
60
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
11865
1
        {
11866
1
            g.NavActivateId = g.NavId;
11867
1
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
11868
1
        }
11869
60
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
11870
27
            g.NavActivateDownId = g.NavId;
11871
60
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
11872
5
            g.NavActivatePressedId = g.NavId;
11873
60
    }
11874
21.3k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11875
0
        g.NavDisableHighlight = true;
11876
21.3k
    if (g.NavActivateId != 0)
11877
21.3k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
11878
11879
    // Process programmatic activation request
11880
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
11881
21.3k
    if (g.NavNextActivateId != 0)
11882
0
    {
11883
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
11884
0
        g.NavActivateFlags = g.NavNextActivateFlags;
11885
0
    }
11886
21.3k
    g.NavNextActivateId = 0;
11887
11888
    // Process move requests
11889
21.3k
    NavUpdateCreateMoveRequest();
11890
21.3k
    if (g.NavMoveDir == ImGuiDir_None)
11891
21.3k
        NavUpdateCreateTabbingRequest();
11892
21.3k
    NavUpdateAnyRequestFlag();
11893
21.3k
    g.NavIdIsAlive = false;
11894
11895
    // Scrolling
11896
21.3k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
11897
2.20k
    {
11898
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
11899
2.20k
        ImGuiWindow* window = g.NavWindow;
11900
2.20k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
11901
2.20k
        const ImGuiDir move_dir = g.NavMoveDir;
11902
2.20k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && move_dir != ImGuiDir_None)
11903
6
        {
11904
6
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11905
2
                SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
11906
6
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
11907
4
                SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
11908
6
        }
11909
11910
        // *Normal* Manual scroll with LStick
11911
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
11912
2.20k
        if (nav_gamepad_active)
11913
0
        {
11914
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
11915
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
11916
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
11917
0
                SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
11918
0
            if (scroll_dir.y != 0.0f)
11919
0
                SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
11920
0
        }
11921
2.20k
    }
11922
11923
    // Always prioritize mouse highlight if navigation is disabled
11924
21.3k
    if (!nav_keyboard_active && !nav_gamepad_active)
11925
0
    {
11926
0
        g.NavDisableHighlight = true;
11927
0
        g.NavDisableMouseHover = set_mouse_pos = false;
11928
0
    }
11929
11930
    // Update mouse position if requested
11931
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
11932
21.3k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
11933
0
    {
11934
0
        io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
11935
0
        io.WantSetMousePos = true;
11936
        //IMGUI_DEBUG_LOG_IO("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
11937
0
    }
11938
11939
    // [DEBUG]
11940
21.3k
    g.NavScoringDebugCount = 0;
11941
#if IMGUI_DEBUG_NAV_RECTS
11942
    if (g.NavWindow)
11943
    {
11944
        ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
11945
        if (1) { for (int layer = 0; layer < 2; layer++) { ImRect r = WindowRectRelToAbs(g.NavWindow, g.NavWindow->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255,200,0,255)); } } // [DEBUG]
11946
        if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
11947
    }
11948
#endif
11949
21.3k
}
11950
11951
void ImGui::NavInitRequestApplyResult()
11952
1
{
11953
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
11954
1
    ImGuiContext& g = *GImGui;
11955
1
    if (!g.NavWindow)
11956
1
        return;
11957
11958
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
11959
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
11960
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
11961
0
    SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
11962
0
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
11963
0
    if (g.NavInitRequestFromMove)
11964
0
        NavRestoreHighlightAfterMove();
11965
0
}
11966
11967
void ImGui::NavUpdateCreateMoveRequest()
11968
21.3k
{
11969
21.3k
    ImGuiContext& g = *GImGui;
11970
21.3k
    ImGuiIO& io = g.IO;
11971
21.3k
    ImGuiWindow* window = g.NavWindow;
11972
21.3k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11973
21.3k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11974
11975
21.3k
    if (g.NavMoveForwardToNextFrame && window != NULL)
11976
0
    {
11977
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
11978
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
11979
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
11980
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
11981
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
11982
0
    }
11983
21.3k
    else
11984
21.3k
    {
11985
        // Initiate directional inputs request
11986
21.3k
        g.NavMoveDir = ImGuiDir_None;
11987
21.3k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
11988
21.3k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
11989
21.3k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
11990
2.20k
        {
11991
2.20k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
11992
2.20k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
11993
2.20k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
11994
2.20k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
11995
2.20k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
11996
2.20k
        }
11997
21.3k
        g.NavMoveClipDir = g.NavMoveDir;
11998
21.3k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
11999
21.3k
    }
12000
12001
    // Update PageUp/PageDown/Home/End scroll
12002
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12003
21.3k
    float scoring_rect_offset_y = 0.0f;
12004
21.3k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12005
2.19k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
12006
21.3k
    if (scoring_rect_offset_y != 0.0f)
12007
0
    {
12008
0
        g.NavScoringNoClipRect = window->InnerRect;
12009
0
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12010
0
    }
12011
12012
    // [DEBUG] Always send a request
12013
#if IMGUI_DEBUG_NAV_SCORING
12014
    if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12015
        g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12016
    if (io.KeyCtrl && g.NavMoveDir == ImGuiDir_None)
12017
    {
12018
        g.NavMoveDir = g.NavMoveDirForDebug;
12019
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12020
    }
12021
#endif
12022
12023
    // Submit
12024
21.3k
    g.NavMoveForwardToNextFrame = false;
12025
21.3k
    if (g.NavMoveDir != ImGuiDir_None)
12026
32
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12027
12028
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12029
21.3k
    if (g.NavMoveSubmitted && g.NavId == 0)
12030
28
    {
12031
28
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12032
28
        g.NavInitRequest = g.NavInitRequestFromMove = true;
12033
28
        g.NavInitResultId = 0;
12034
28
        g.NavDisableHighlight = false;
12035
28
    }
12036
12037
    // When using gamepad, we project the reference nav bounding box into window visible area.
12038
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12039
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12040
21.3k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12041
0
    {
12042
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12043
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12044
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12045
12046
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12047
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
12048
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12049
12050
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12051
0
        {
12052
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12053
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12054
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12055
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12056
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12057
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12058
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12059
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12060
0
            g.NavId = 0;
12061
0
        }
12062
0
    }
12063
12064
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
12065
21.3k
    ImRect scoring_rect;
12066
21.3k
    if (window != NULL)
12067
2.20k
    {
12068
2.20k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12069
2.20k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12070
2.20k
        scoring_rect.TranslateY(scoring_rect_offset_y);
12071
2.20k
        scoring_rect.Min.x = ImMin(scoring_rect.Min.x + 1.0f, scoring_rect.Max.x);
12072
2.20k
        scoring_rect.Max.x = scoring_rect.Min.x;
12073
2.20k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12074
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12075
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12076
2.20k
    }
12077
21.3k
    g.NavScoringRect = scoring_rect;
12078
21.3k
    g.NavScoringNoClipRect.Add(scoring_rect);
12079
21.3k
}
12080
12081
void ImGui::NavUpdateCreateTabbingRequest()
12082
21.3k
{
12083
21.3k
    ImGuiContext& g = *GImGui;
12084
21.3k
    ImGuiWindow* window = g.NavWindow;
12085
21.3k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12086
21.3k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12087
19.1k
        return;
12088
12089
2.17k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12090
2.17k
    if (!tab_pressed)
12091
2.16k
        return;
12092
12093
    // Initiate tabbing request
12094
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12095
    // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.
12096
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12097
8
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12098
8
    if (nav_keyboard_active)
12099
8
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12100
0
    else
12101
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12102
8
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12103
8
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12104
8
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12105
8
    g.NavTabbingCounter = -1;
12106
8
}
12107
12108
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12109
void ImGui::NavMoveRequestApplyResult()
12110
30
{
12111
30
    ImGuiContext& g = *GImGui;
12112
#if IMGUI_DEBUG_NAV_SCORING
12113
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12114
        return;
12115
#endif
12116
12117
    // Select which result to use
12118
30
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12119
12120
    // Tabbing forward wrap
12121
30
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && result == NULL)
12122
5
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12123
1
            result = &g.NavTabbingResultFirst;
12124
12125
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12126
30
    if (result == NULL)
12127
29
    {
12128
29
        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
12129
4
            g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
12130
29
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
12131
3
            NavRestoreHighlightAfterMove();
12132
29
        return;
12133
29
    }
12134
12135
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12136
1
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12137
0
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12138
0
            result = &g.NavMoveResultLocalVisible;
12139
12140
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12141
1
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12142
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12143
0
            result = &g.NavMoveResultOther;
12144
1
    IM_ASSERT(g.NavWindow && result->Window);
12145
12146
    // Scroll to keep newly navigated item fully into view.
12147
1
    if (g.NavLayer == ImGuiNavLayer_Main)
12148
1
    {
12149
1
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12150
0
        {
12151
            // FIXME: Should remove this
12152
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12153
0
            SetScrollY(result->Window, scroll_target);
12154
0
        }
12155
1
        else
12156
1
        {
12157
1
            ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12158
1
            ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12159
1
        }
12160
1
    }
12161
12162
1
    if (g.NavWindow != result->Window)
12163
0
    {
12164
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12165
0
        g.NavWindow = result->Window;
12166
0
    }
12167
1
    if (g.ActiveId != result->ID)
12168
1
        ClearActiveID();
12169
1
    if (g.NavId != result->ID)
12170
0
    {
12171
        // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12172
0
        g.NavJustMovedToId = result->ID;
12173
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12174
0
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12175
0
    }
12176
12177
    // Focus
12178
1
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12179
1
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12180
12181
    // Tabbing: Activates Inputable or Focus non-Inputable
12182
1
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable))
12183
0
    {
12184
0
        g.NavNextActivateId = result->ID;
12185
0
        g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
12186
0
        g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
12187
0
    }
12188
12189
    // Activate
12190
1
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12191
0
    {
12192
0
        g.NavNextActivateId = result->ID;
12193
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12194
0
    }
12195
12196
    // Enable nav highlight
12197
1
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
12198
1
        NavRestoreHighlightAfterMove();
12199
1
}
12200
12201
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12202
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12203
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12204
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12205
static void ImGui::NavUpdateCancelRequest()
12206
21.3k
{
12207
21.3k
    ImGuiContext& g = *GImGui;
12208
21.3k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12209
21.3k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12210
21.3k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12211
21.0k
        return;
12212
12213
331
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12214
331
    if (g.ActiveId != 0)
12215
12
    {
12216
12
        ClearActiveID();
12217
12
    }
12218
319
    else if (g.NavLayer != ImGuiNavLayer_Main)
12219
0
    {
12220
        // Leave the "menu" layer
12221
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12222
0
        NavRestoreHighlightAfterMove();
12223
0
    }
12224
319
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12225
26
    {
12226
        // Exit child window
12227
26
        ImGuiWindow* child_window = g.NavWindow;
12228
26
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12229
26
        IM_ASSERT(child_window->ChildId != 0);
12230
26
        ImRect child_rect = child_window->Rect();
12231
26
        FocusWindow(parent_window);
12232
26
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12233
26
        NavRestoreHighlightAfterMove();
12234
26
    }
12235
293
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12236
0
    {
12237
        // Close open popup/menu
12238
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12239
0
    }
12240
293
    else
12241
293
    {
12242
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12243
293
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12244
9
            g.NavWindow->NavLastIds[0] = 0;
12245
293
        g.NavId = 0;
12246
293
    }
12247
331
}
12248
12249
// Handle PageUp/PageDown/Home/End keys
12250
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12251
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12252
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12253
static float ImGui::NavUpdatePageUpPageDown()
12254
2.19k
{
12255
2.19k
    ImGuiContext& g = *GImGui;
12256
2.19k
    ImGuiWindow* window = g.NavWindow;
12257
2.19k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12258
0
        return 0.0f;
12259
12260
2.19k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12261
2.19k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12262
2.19k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12263
2.19k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12264
2.19k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12265
1.91k
        return 0.0f;
12266
12267
287
    if (g.NavLayer != ImGuiNavLayer_Main)
12268
28
        NavRestoreLayer(ImGuiNavLayer_Main);
12269
12270
287
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)
12271
48
    {
12272
        // Fallback manual-scroll when window has no navigable item
12273
48
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12274
4
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12275
44
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12276
1
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12277
43
        else if (home_pressed)
12278
1
            SetScrollY(window, 0.0f);
12279
42
        else if (end_pressed)
12280
2
            SetScrollY(window, window->ScrollMax.y);
12281
48
    }
12282
239
    else
12283
239
    {
12284
239
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12285
239
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12286
239
        float nav_scoring_rect_offset_y = 0.0f;
12287
239
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12288
25
        {
12289
25
            nav_scoring_rect_offset_y = -page_offset_y;
12290
25
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12291
25
            g.NavMoveClipDir = ImGuiDir_Up;
12292
25
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12293
25
        }
12294
214
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12295
0
        {
12296
0
            nav_scoring_rect_offset_y = +page_offset_y;
12297
0
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12298
0
            g.NavMoveClipDir = ImGuiDir_Down;
12299
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12300
0
        }
12301
214
        else if (home_pressed)
12302
0
        {
12303
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12304
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12305
            // Preserve current horizontal position if we have any.
12306
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12307
0
            if (nav_rect_rel.IsInverted())
12308
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12309
0
            g.NavMoveDir = ImGuiDir_Down;
12310
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12311
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12312
0
        }
12313
214
        else if (end_pressed)
12314
0
        {
12315
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12316
0
            if (nav_rect_rel.IsInverted())
12317
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12318
0
            g.NavMoveDir = ImGuiDir_Up;
12319
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12320
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12321
0
        }
12322
239
        return nav_scoring_rect_offset_y;
12323
239
    }
12324
48
    return 0.0f;
12325
287
}
12326
12327
static void ImGui::NavEndFrame()
12328
21.3k
{
12329
21.3k
    ImGuiContext& g = *GImGui;
12330
12331
    // Show CTRL+TAB list window
12332
21.3k
    if (g.NavWindowingTarget != NULL)
12333
0
        NavUpdateWindowingOverlay();
12334
12335
    // Perform wrap-around in menus
12336
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12337
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12338
21.3k
    const ImGuiNavMoveFlags wanted_flags = ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY;
12339
21.3k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & wanted_flags) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12340
0
        NavUpdateCreateWrappingRequest();
12341
21.3k
}
12342
12343
static void ImGui::NavUpdateCreateWrappingRequest()
12344
0
{
12345
0
    ImGuiContext& g = *GImGui;
12346
0
    ImGuiWindow* window = g.NavWindow;
12347
12348
0
    bool do_forward = false;
12349
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12350
0
    ImGuiDir clip_dir = g.NavMoveDir;
12351
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12352
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12353
0
    {
12354
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12355
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12356
0
        {
12357
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12358
0
            clip_dir = ImGuiDir_Up;
12359
0
        }
12360
0
        do_forward = true;
12361
0
    }
12362
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12363
0
    {
12364
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12365
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12366
0
        {
12367
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12368
0
            clip_dir = ImGuiDir_Down;
12369
0
        }
12370
0
        do_forward = true;
12371
0
    }
12372
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12373
0
    {
12374
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12375
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12376
0
        {
12377
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12378
0
            clip_dir = ImGuiDir_Left;
12379
0
        }
12380
0
        do_forward = true;
12381
0
    }
12382
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12383
0
    {
12384
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12385
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12386
0
        {
12387
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12388
0
            clip_dir = ImGuiDir_Right;
12389
0
        }
12390
0
        do_forward = true;
12391
0
    }
12392
0
    if (!do_forward)
12393
0
        return;
12394
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12395
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12396
0
}
12397
12398
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12399
0
{
12400
0
    ImGuiContext& g = *GImGui;
12401
0
    IM_UNUSED(g);
12402
0
    int order = window->FocusOrder;
12403
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12404
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12405
0
    return order;
12406
0
}
12407
12408
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12409
0
{
12410
0
    ImGuiContext& g = *GImGui;
12411
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12412
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12413
0
            return g.WindowsFocusOrder[i];
12414
0
    return NULL;
12415
0
}
12416
12417
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12418
0
{
12419
0
    ImGuiContext& g = *GImGui;
12420
0
    IM_ASSERT(g.NavWindowingTarget);
12421
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12422
0
        return;
12423
12424
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12425
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12426
0
    if (!window_target)
12427
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12428
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12429
0
    {
12430
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12431
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12432
0
    }
12433
0
    g.NavWindowingToggleLayer = false;
12434
0
}
12435
12436
// Windowing management mode
12437
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12438
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12439
static void ImGui::NavUpdateWindowing()
12440
21.3k
{
12441
21.3k
    ImGuiContext& g = *GImGui;
12442
21.3k
    ImGuiIO& io = g.IO;
12443
12444
21.3k
    ImGuiWindow* apply_focus_window = NULL;
12445
21.3k
    bool apply_toggle_layer = false;
12446
12447
21.3k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12448
21.3k
    bool allow_windowing = (modal_window == NULL);
12449
21.3k
    if (!allow_windowing)
12450
0
        g.NavWindowingTarget = NULL;
12451
12452
    // Fade out
12453
21.3k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12454
0
    {
12455
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12456
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12457
0
            g.NavWindowingTargetAnim = NULL;
12458
0
    }
12459
12460
    // Start CTRL+Tab or Square+L/R window selection
12461
21.3k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
12462
21.3k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12463
21.3k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12464
21.3k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12465
21.3k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12466
21.3k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12467
21.3k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12468
21.3k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12469
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12470
0
        {
12471
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12472
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12473
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12474
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
12475
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
12476
12477
            // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
12478
0
            if (keyboard_next_window || keyboard_prev_window)
12479
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
12480
0
        }
12481
12482
    // Gamepad update
12483
21.3k
    g.NavWindowingTimer += io.DeltaTime;
12484
21.3k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
12485
0
    {
12486
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
12487
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
12488
12489
        // Select window to focus
12490
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
12491
0
        if (focus_change_dir != 0)
12492
0
        {
12493
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
12494
0
            g.NavWindowingHighlightAlpha = 1.0f;
12495
0
        }
12496
12497
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
12498
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
12499
0
        {
12500
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
12501
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
12502
0
                apply_toggle_layer = true;
12503
0
            else if (!g.NavWindowingToggleLayer)
12504
0
                apply_focus_window = g.NavWindowingTarget;
12505
0
            g.NavWindowingTarget = NULL;
12506
0
        }
12507
0
    }
12508
12509
    // Keyboard: Focus
12510
21.3k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
12511
0
    {
12512
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
12513
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
12514
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
12515
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
12516
0
        if (keyboard_next_window || keyboard_prev_window)
12517
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
12518
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
12519
0
            apply_focus_window = g.NavWindowingTarget;
12520
0
    }
12521
12522
    // Keyboard: Press and Release ALT to toggle menu layer
12523
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
12524
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
12525
21.3k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
12526
0
    {
12527
0
        g.NavWindowingToggleLayer = true;
12528
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
12529
0
    }
12530
21.3k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
12531
0
    {
12532
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
12533
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
12534
        // We cancel toggling nav layer if an owner has claimed the key.
12535
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
12536
0
            g.NavWindowingToggleLayer = false;
12537
12538
        // Apply layer toggle on release
12539
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
12540
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
12541
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
12542
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
12543
0
                    apply_toggle_layer = true;
12544
0
        if (!IsKeyDown(ImGuiMod_Alt))
12545
0
            g.NavWindowingToggleLayer = false;
12546
0
    }
12547
12548
    // Move window
12549
21.3k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
12550
0
    {
12551
0
        ImVec2 nav_move_dir;
12552
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
12553
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
12554
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
12555
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12556
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
12557
0
        {
12558
0
            const float NAV_MOVE_SPEED = 800.0f;
12559
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
12560
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
12561
0
            g.NavDisableMouseHover = true;
12562
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaPos);
12563
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
12564
0
            {
12565
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
12566
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
12567
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
12568
0
            }
12569
0
        }
12570
0
    }
12571
12572
    // Apply final focus
12573
21.3k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
12574
0
    {
12575
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
12576
0
        ClearActiveID();
12577
0
        NavRestoreHighlightAfterMove();
12578
0
        apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
12579
0
        ClosePopupsOverWindow(apply_focus_window, false);
12580
0
        FocusWindow(apply_focus_window);
12581
0
        if (apply_focus_window->NavLastIds[0] == 0)
12582
0
            NavInitWindow(apply_focus_window, false);
12583
12584
        // If the window has ONLY a menu layer (no main layer), select it directly
12585
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
12586
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
12587
        // the target window as already been previewed once.
12588
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
12589
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
12590
        // won't be valid.
12591
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
12592
0
            g.NavLayer = ImGuiNavLayer_Menu;
12593
12594
        // Request OS level focus
12595
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
12596
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
12597
0
    }
12598
21.3k
    if (apply_focus_window)
12599
0
        g.NavWindowingTarget = NULL;
12600
12601
    // Apply menu/layer toggle
12602
21.3k
    if (apply_toggle_layer && g.NavWindow)
12603
0
    {
12604
0
        ClearActiveID();
12605
12606
        // Move to parent menu if necessary
12607
0
        ImGuiWindow* new_nav_window = g.NavWindow;
12608
0
        while (new_nav_window->ParentWindow
12609
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
12610
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
12611
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12612
0
            new_nav_window = new_nav_window->ParentWindow;
12613
0
        if (new_nav_window != g.NavWindow)
12614
0
        {
12615
0
            ImGuiWindow* old_nav_window = g.NavWindow;
12616
0
            FocusWindow(new_nav_window);
12617
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
12618
0
        }
12619
12620
        // Toggle layer
12621
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
12622
0
        if (new_nav_layer != g.NavLayer)
12623
0
        {
12624
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
12625
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
12626
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
12627
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
12628
0
            NavRestoreLayer(new_nav_layer);
12629
0
            NavRestoreHighlightAfterMove();
12630
0
        }
12631
0
    }
12632
21.3k
}
12633
12634
// Window has already passed the IsWindowNavFocusable()
12635
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
12636
0
{
12637
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12638
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
12639
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
12640
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
12641
0
    if (window->DockNodeAsHost)
12642
0
        return "(Dock node)"; // Not normally shown to user.
12643
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
12644
0
}
12645
12646
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
12647
void ImGui::NavUpdateWindowingOverlay()
12648
0
{
12649
0
    ImGuiContext& g = *GImGui;
12650
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
12651
12652
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
12653
0
        return;
12654
12655
0
    if (g.NavWindowingListWindow == NULL)
12656
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
12657
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
12658
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
12659
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
12660
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
12661
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
12662
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
12663
0
    {
12664
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
12665
0
        IM_ASSERT(window != NULL); // Fix static analyzers
12666
0
        if (!IsWindowNavFocusable(window))
12667
0
            continue;
12668
0
        const char* label = window->Name;
12669
0
        if (label == FindRenderedTextEnd(label))
12670
0
            label = GetFallbackWindowNameForWindowingList(window);
12671
0
        Selectable(label, g.NavWindowingTarget == window);
12672
0
    }
12673
0
    End();
12674
0
    PopStyleVar();
12675
0
}
12676
12677
12678
//-----------------------------------------------------------------------------
12679
// [SECTION] DRAG AND DROP
12680
//-----------------------------------------------------------------------------
12681
12682
bool ImGui::IsDragDropActive()
12683
0
{
12684
0
    ImGuiContext& g = *GImGui;
12685
0
    return g.DragDropActive;
12686
0
}
12687
12688
void ImGui::ClearDragDrop()
12689
0
{
12690
0
    ImGuiContext& g = *GImGui;
12691
0
    g.DragDropActive = false;
12692
0
    g.DragDropPayload.Clear();
12693
0
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
12694
0
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
12695
0
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
12696
0
    g.DragDropAcceptFrameCount = -1;
12697
12698
0
    g.DragDropPayloadBufHeap.clear();
12699
0
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12700
0
}
12701
12702
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
12703
// If the item has an identifier:
12704
// - This assume/require the item to be activated (typically via ButtonBehavior).
12705
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
12706
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
12707
// If the item has no identifier:
12708
// - Currently always assume left mouse button.
12709
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
12710
0
{
12711
0
    ImGuiContext& g = *GImGui;
12712
0
    ImGuiWindow* window = g.CurrentWindow;
12713
12714
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
12715
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
12716
0
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
12717
12718
0
    bool source_drag_active = false;
12719
0
    ImGuiID source_id = 0;
12720
0
    ImGuiID source_parent_id = 0;
12721
0
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
12722
0
    {
12723
0
        source_id = g.LastItemData.ID;
12724
0
        if (source_id != 0)
12725
0
        {
12726
            // Common path: items with ID
12727
0
            if (g.ActiveId != source_id)
12728
0
                return false;
12729
0
            if (g.ActiveIdMouseButton != -1)
12730
0
                mouse_button = g.ActiveIdMouseButton;
12731
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12732
0
                return false;
12733
0
            g.ActiveIdAllowOverlap = false;
12734
0
        }
12735
0
        else
12736
0
        {
12737
            // Uncommon path: items without ID
12738
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12739
0
                return false;
12740
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
12741
0
                return false;
12742
12743
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
12744
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
12745
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
12746
0
            {
12747
0
                IM_ASSERT(0);
12748
0
                return false;
12749
0
            }
12750
12751
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
12752
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
12753
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
12754
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
12755
            // Rely on keeping other window->LastItemXXX fields intact.
12756
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
12757
0
            KeepAliveID(source_id);
12758
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);
12759
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
12760
0
            {
12761
0
                SetActiveID(source_id, window);
12762
0
                FocusWindow(window);
12763
0
            }
12764
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
12765
0
                g.ActiveIdAllowOverlap = is_hovered;
12766
0
        }
12767
0
        if (g.ActiveId != source_id)
12768
0
            return false;
12769
0
        source_parent_id = window->IDStack.back();
12770
0
        source_drag_active = IsMouseDragging(mouse_button);
12771
12772
        // Disable navigation and key inputs while dragging + cancel existing request if any
12773
0
        SetActiveIdUsingAllKeyboardKeys();
12774
0
    }
12775
0
    else
12776
0
    {
12777
0
        window = NULL;
12778
0
        source_id = ImHashStr("#SourceExtern");
12779
0
        source_drag_active = true;
12780
0
    }
12781
12782
0
    if (source_drag_active)
12783
0
    {
12784
0
        if (!g.DragDropActive)
12785
0
        {
12786
0
            IM_ASSERT(source_id != 0);
12787
0
            ClearDragDrop();
12788
0
            ImGuiPayload& payload = g.DragDropPayload;
12789
0
            payload.SourceId = source_id;
12790
0
            payload.SourceParentId = source_parent_id;
12791
0
            g.DragDropActive = true;
12792
0
            g.DragDropSourceFlags = flags;
12793
0
            g.DragDropMouseButton = mouse_button;
12794
0
            if (payload.SourceId == g.ActiveId)
12795
0
                g.ActiveIdNoClearOnFocusLoss = true;
12796
0
        }
12797
0
        g.DragDropSourceFrameCount = g.FrameCount;
12798
0
        g.DragDropWithinSource = true;
12799
12800
0
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12801
0
        {
12802
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
12803
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
12804
0
            bool ret = BeginTooltip();
12805
0
            IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
12806
0
            IM_UNUSED(ret);
12807
12808
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
12809
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(g.CurrentWindow);
12810
0
        }
12811
12812
0
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
12813
0
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
12814
12815
0
        return true;
12816
0
    }
12817
0
    return false;
12818
0
}
12819
12820
void ImGui::EndDragDropSource()
12821
0
{
12822
0
    ImGuiContext& g = *GImGui;
12823
0
    IM_ASSERT(g.DragDropActive);
12824
0
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
12825
12826
0
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12827
0
        EndTooltip();
12828
12829
    // Discard the drag if have not called SetDragDropPayload()
12830
0
    if (g.DragDropPayload.DataFrameCount == -1)
12831
0
        ClearDragDrop();
12832
0
    g.DragDropWithinSource = false;
12833
0
}
12834
12835
// Use 'cond' to choose to submit payload on drag start or every frame
12836
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
12837
0
{
12838
0
    ImGuiContext& g = *GImGui;
12839
0
    ImGuiPayload& payload = g.DragDropPayload;
12840
0
    if (cond == 0)
12841
0
        cond = ImGuiCond_Always;
12842
12843
0
    IM_ASSERT(type != NULL);
12844
0
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
12845
0
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
12846
0
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
12847
0
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
12848
12849
0
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
12850
0
    {
12851
        // Copy payload
12852
0
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
12853
0
        g.DragDropPayloadBufHeap.resize(0);
12854
0
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
12855
0
        {
12856
            // Store in heap
12857
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
12858
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
12859
0
            memcpy(payload.Data, data, data_size);
12860
0
        }
12861
0
        else if (data_size > 0)
12862
0
        {
12863
            // Store locally
12864
0
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12865
0
            payload.Data = g.DragDropPayloadBufLocal;
12866
0
            memcpy(payload.Data, data, data_size);
12867
0
        }
12868
0
        else
12869
0
        {
12870
0
            payload.Data = NULL;
12871
0
        }
12872
0
        payload.DataSize = (int)data_size;
12873
0
    }
12874
0
    payload.DataFrameCount = g.FrameCount;
12875
12876
    // Return whether the payload has been accepted
12877
0
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
12878
0
}
12879
12880
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
12881
0
{
12882
0
    ImGuiContext& g = *GImGui;
12883
0
    if (!g.DragDropActive)
12884
0
        return false;
12885
12886
0
    ImGuiWindow* window = g.CurrentWindow;
12887
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12888
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
12889
0
        return false;
12890
0
    IM_ASSERT(id != 0);
12891
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
12892
0
        return false;
12893
0
    if (window->SkipItems)
12894
0
        return false;
12895
12896
0
    IM_ASSERT(g.DragDropWithinTarget == false);
12897
0
    g.DragDropTargetRect = bb;
12898
0
    g.DragDropTargetId = id;
12899
0
    g.DragDropWithinTarget = true;
12900
0
    return true;
12901
0
}
12902
12903
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
12904
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
12905
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
12906
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
12907
bool ImGui::BeginDragDropTarget()
12908
0
{
12909
0
    ImGuiContext& g = *GImGui;
12910
0
    if (!g.DragDropActive)
12911
0
        return false;
12912
12913
0
    ImGuiWindow* window = g.CurrentWindow;
12914
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
12915
0
        return false;
12916
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12917
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
12918
0
        return false;
12919
12920
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
12921
0
    ImGuiID id = g.LastItemData.ID;
12922
0
    if (id == 0)
12923
0
    {
12924
0
        id = window->GetIDFromRectangle(display_rect);
12925
0
        KeepAliveID(id);
12926
0
    }
12927
0
    if (g.DragDropPayload.SourceId == id)
12928
0
        return false;
12929
12930
0
    IM_ASSERT(g.DragDropWithinTarget == false);
12931
0
    g.DragDropTargetRect = display_rect;
12932
0
    g.DragDropTargetId = id;
12933
0
    g.DragDropWithinTarget = true;
12934
0
    return true;
12935
0
}
12936
12937
bool ImGui::IsDragDropPayloadBeingAccepted()
12938
2
{
12939
2
    ImGuiContext& g = *GImGui;
12940
2
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
12941
2
}
12942
12943
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
12944
0
{
12945
0
    ImGuiContext& g = *GImGui;
12946
0
    ImGuiWindow* window = g.CurrentWindow;
12947
0
    ImGuiPayload& payload = g.DragDropPayload;
12948
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
12949
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
12950
0
    if (type != NULL && !payload.IsDataType(type))
12951
0
        return NULL;
12952
12953
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
12954
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
12955
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
12956
0
    ImRect r = g.DragDropTargetRect;
12957
0
    float r_surface = r.GetWidth() * r.GetHeight();
12958
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
12959
0
        return NULL;
12960
12961
0
    g.DragDropAcceptFlags = flags;
12962
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
12963
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
12964
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
12965
12966
    // Render default drop visuals
12967
0
    payload.Preview = was_accepted_previously;
12968
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
12969
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
12970
0
        window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
12971
12972
0
    g.DragDropAcceptFrameCount = g.FrameCount;
12973
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
12974
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
12975
0
        return NULL;
12976
12977
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
12978
0
    return &payload;
12979
0
}
12980
12981
// FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
12982
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
12983
0
{
12984
0
    GetWindowDrawList()->AddRect(bb.Min - ImVec2(3.5f, 3.5f), bb.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
12985
0
}
12986
12987
const ImGuiPayload* ImGui::GetDragDropPayload()
12988
0
{
12989
0
    ImGuiContext& g = *GImGui;
12990
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
12991
0
}
12992
12993
void ImGui::EndDragDropTarget()
12994
0
{
12995
0
    ImGuiContext& g = *GImGui;
12996
0
    IM_ASSERT(g.DragDropActive);
12997
0
    IM_ASSERT(g.DragDropWithinTarget);
12998
0
    g.DragDropWithinTarget = false;
12999
13000
    // Clear drag and drop state payload right after delivery
13001
0
    if (g.DragDropPayload.Delivery)
13002
0
        ClearDragDrop();
13003
0
}
13004
13005
//-----------------------------------------------------------------------------
13006
// [SECTION] LOGGING/CAPTURING
13007
//-----------------------------------------------------------------------------
13008
// All text output from the interface can be captured into tty/file/clipboard.
13009
// By default, tree nodes are automatically opened during logging.
13010
//-----------------------------------------------------------------------------
13011
13012
// Pass text data straight to log (without being displayed)
13013
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13014
0
{
13015
0
    if (g.LogFile)
13016
0
    {
13017
0
        g.LogBuffer.Buf.resize(0);
13018
0
        g.LogBuffer.appendfv(fmt, args);
13019
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13020
0
    }
13021
0
    else
13022
0
    {
13023
0
        g.LogBuffer.appendfv(fmt, args);
13024
0
    }
13025
0
}
13026
13027
void ImGui::LogText(const char* fmt, ...)
13028
0
{
13029
0
    ImGuiContext& g = *GImGui;
13030
0
    if (!g.LogEnabled)
13031
0
        return;
13032
13033
0
    va_list args;
13034
0
    va_start(args, fmt);
13035
0
    LogTextV(g, fmt, args);
13036
0
    va_end(args);
13037
0
}
13038
13039
void ImGui::LogTextV(const char* fmt, va_list args)
13040
0
{
13041
0
    ImGuiContext& g = *GImGui;
13042
0
    if (!g.LogEnabled)
13043
0
        return;
13044
13045
0
    LogTextV(g, fmt, args);
13046
0
}
13047
13048
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13049
// We split text into individual lines to add current tree level padding
13050
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13051
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13052
0
{
13053
0
    ImGuiContext& g = *GImGui;
13054
0
    ImGuiWindow* window = g.CurrentWindow;
13055
13056
0
    const char* prefix = g.LogNextPrefix;
13057
0
    const char* suffix = g.LogNextSuffix;
13058
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13059
13060
0
    if (!text_end)
13061
0
        text_end = FindRenderedTextEnd(text, text_end);
13062
13063
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13064
0
    if (ref_pos)
13065
0
        g.LogLinePosY = ref_pos->y;
13066
0
    if (log_new_line)
13067
0
    {
13068
0
        LogText(IM_NEWLINE);
13069
0
        g.LogLineFirstItem = true;
13070
0
    }
13071
13072
0
    if (prefix)
13073
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13074
13075
    // Re-adjust padding if we have popped out of our starting depth
13076
0
    if (g.LogDepthRef > window->DC.TreeDepth)
13077
0
        g.LogDepthRef = window->DC.TreeDepth;
13078
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13079
13080
0
    const char* text_remaining = text;
13081
0
    for (;;)
13082
0
    {
13083
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13084
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13085
0
        const char* line_start = text_remaining;
13086
0
        const char* line_end = ImStreolRange(line_start, text_end);
13087
0
        const bool is_last_line = (line_end == text_end);
13088
0
        if (line_start != line_end || !is_last_line)
13089
0
        {
13090
0
            const int line_length = (int)(line_end - line_start);
13091
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13092
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
13093
0
            g.LogLineFirstItem = false;
13094
0
            if (*line_end == '\n')
13095
0
            {
13096
0
                LogText(IM_NEWLINE);
13097
0
                g.LogLineFirstItem = true;
13098
0
            }
13099
0
        }
13100
0
        if (is_last_line)
13101
0
            break;
13102
0
        text_remaining = line_end + 1;
13103
0
    }
13104
13105
0
    if (suffix)
13106
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
13107
0
}
13108
13109
// Start logging/capturing text output
13110
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13111
0
{
13112
0
    ImGuiContext& g = *GImGui;
13113
0
    ImGuiWindow* window = g.CurrentWindow;
13114
0
    IM_ASSERT(g.LogEnabled == false);
13115
0
    IM_ASSERT(g.LogFile == NULL);
13116
0
    IM_ASSERT(g.LogBuffer.empty());
13117
0
    g.LogEnabled = true;
13118
0
    g.LogType = type;
13119
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13120
0
    g.LogDepthRef = window->DC.TreeDepth;
13121
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
13122
0
    g.LogLinePosY = FLT_MAX;
13123
0
    g.LogLineFirstItem = true;
13124
0
}
13125
13126
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13127
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13128
0
{
13129
0
    ImGuiContext& g = *GImGui;
13130
0
    g.LogNextPrefix = prefix;
13131
0
    g.LogNextSuffix = suffix;
13132
0
}
13133
13134
void ImGui::LogToTTY(int auto_open_depth)
13135
0
{
13136
0
    ImGuiContext& g = *GImGui;
13137
0
    if (g.LogEnabled)
13138
0
        return;
13139
0
    IM_UNUSED(auto_open_depth);
13140
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13141
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
13142
0
    g.LogFile = stdout;
13143
0
#endif
13144
0
}
13145
13146
// Start logging/capturing text output to given file
13147
void ImGui::LogToFile(int auto_open_depth, const char* filename)
13148
0
{
13149
0
    ImGuiContext& g = *GImGui;
13150
0
    if (g.LogEnabled)
13151
0
        return;
13152
13153
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13154
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13155
    // By opening the file in binary mode "ab" we have consistent output everywhere.
13156
0
    if (!filename)
13157
0
        filename = g.IO.LogFilename;
13158
0
    if (!filename || !filename[0])
13159
0
        return;
13160
0
    ImFileHandle f = ImFileOpen(filename, "ab");
13161
0
    if (!f)
13162
0
    {
13163
0
        IM_ASSERT(0);
13164
0
        return;
13165
0
    }
13166
13167
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
13168
0
    g.LogFile = f;
13169
0
}
13170
13171
// Start logging/capturing text output to clipboard
13172
void ImGui::LogToClipboard(int auto_open_depth)
13173
0
{
13174
0
    ImGuiContext& g = *GImGui;
13175
0
    if (g.LogEnabled)
13176
0
        return;
13177
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
13178
0
}
13179
13180
void ImGui::LogToBuffer(int auto_open_depth)
13181
0
{
13182
0
    ImGuiContext& g = *GImGui;
13183
0
    if (g.LogEnabled)
13184
0
        return;
13185
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13186
0
}
13187
13188
void ImGui::LogFinish()
13189
42.7k
{
13190
42.7k
    ImGuiContext& g = *GImGui;
13191
42.7k
    if (!g.LogEnabled)
13192
42.7k
        return;
13193
13194
0
    LogText(IM_NEWLINE);
13195
0
    switch (g.LogType)
13196
0
    {
13197
0
    case ImGuiLogType_TTY:
13198
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13199
0
        fflush(g.LogFile);
13200
0
#endif
13201
0
        break;
13202
0
    case ImGuiLogType_File:
13203
0
        ImFileClose(g.LogFile);
13204
0
        break;
13205
0
    case ImGuiLogType_Buffer:
13206
0
        break;
13207
0
    case ImGuiLogType_Clipboard:
13208
0
        if (!g.LogBuffer.empty())
13209
0
            SetClipboardText(g.LogBuffer.begin());
13210
0
        break;
13211
0
    case ImGuiLogType_None:
13212
0
        IM_ASSERT(0);
13213
0
        break;
13214
0
    }
13215
13216
0
    g.LogEnabled = false;
13217
0
    g.LogType = ImGuiLogType_None;
13218
0
    g.LogFile = NULL;
13219
0
    g.LogBuffer.clear();
13220
0
}
13221
13222
// Helper to display logging buttons
13223
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13224
void ImGui::LogButtons()
13225
0
{
13226
0
    ImGuiContext& g = *GImGui;
13227
13228
0
    PushID("LogButtons");
13229
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13230
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13231
#else
13232
    const bool log_to_tty = false;
13233
#endif
13234
0
    const bool log_to_file = Button("Log To File"); SameLine();
13235
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13236
0
    PushTabStop(false);
13237
0
    SetNextItemWidth(80.0f);
13238
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13239
0
    PopTabStop();
13240
0
    PopID();
13241
13242
    // Start logging at the end of the function so that the buttons don't appear in the log
13243
0
    if (log_to_tty)
13244
0
        LogToTTY();
13245
0
    if (log_to_file)
13246
0
        LogToFile();
13247
0
    if (log_to_clipboard)
13248
0
        LogToClipboard();
13249
0
}
13250
13251
13252
//-----------------------------------------------------------------------------
13253
// [SECTION] SETTINGS
13254
//-----------------------------------------------------------------------------
13255
// - UpdateSettings() [Internal]
13256
// - MarkIniSettingsDirty() [Internal]
13257
// - FindSettingsHandler() [Internal]
13258
// - ClearIniSettings() [Internal]
13259
// - LoadIniSettingsFromDisk()
13260
// - LoadIniSettingsFromMemory()
13261
// - SaveIniSettingsToDisk()
13262
// - SaveIniSettingsToMemory()
13263
//-----------------------------------------------------------------------------
13264
// - CreateNewWindowSettings() [Internal]
13265
// - FindWindowSettingsByID() [Internal]
13266
// - FindWindowSettingsByWindow() [Internal]
13267
// - ClearWindowSettings() [Internal]
13268
// - WindowSettingsHandler_***() [Internal]
13269
//-----------------------------------------------------------------------------
13270
13271
// Called by NewFrame()
13272
void ImGui::UpdateSettings()
13273
21.3k
{
13274
    // Load settings on first frame (if not explicitly loaded manually before)
13275
21.3k
    ImGuiContext& g = *GImGui;
13276
21.3k
    if (!g.SettingsLoaded)
13277
1
    {
13278
1
        IM_ASSERT(g.SettingsWindows.empty());
13279
1
        if (g.IO.IniFilename)
13280
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13281
1
        g.SettingsLoaded = true;
13282
1
    }
13283
13284
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13285
21.3k
    if (g.SettingsDirtyTimer > 0.0f)
13286
600
    {
13287
600
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13288
600
        if (g.SettingsDirtyTimer <= 0.0f)
13289
2
        {
13290
2
            if (g.IO.IniFilename != NULL)
13291
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13292
2
            else
13293
2
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13294
2
            g.SettingsDirtyTimer = 0.0f;
13295
2
        }
13296
600
    }
13297
21.3k
}
13298
13299
void ImGui::MarkIniSettingsDirty()
13300
0
{
13301
0
    ImGuiContext& g = *GImGui;
13302
0
    if (g.SettingsDirtyTimer <= 0.0f)
13303
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13304
0
}
13305
13306
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13307
1.28k
{
13308
1.28k
    ImGuiContext& g = *GImGui;
13309
1.28k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13310
6
        if (g.SettingsDirtyTimer <= 0.0f)
13311
2
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13312
1.28k
}
13313
13314
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13315
2
{
13316
2
    ImGuiContext& g = *GImGui;
13317
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13318
2
    g.SettingsHandlers.push_back(*handler);
13319
2
}
13320
13321
void ImGui::RemoveSettingsHandler(const char* type_name)
13322
0
{
13323
0
    ImGuiContext& g = *GImGui;
13324
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13325
0
        g.SettingsHandlers.erase(handler);
13326
0
}
13327
13328
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13329
2
{
13330
2
    ImGuiContext& g = *GImGui;
13331
2
    const ImGuiID type_hash = ImHashStr(type_name);
13332
3
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13333
1
        if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
13334
0
            return &g.SettingsHandlers[handler_n];
13335
2
    return NULL;
13336
2
}
13337
13338
// Clear all settings (windows, tables, docking etc.)
13339
void ImGui::ClearIniSettings()
13340
0
{
13341
0
    ImGuiContext& g = *GImGui;
13342
0
    g.SettingsIniData.clear();
13343
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13344
0
        if (g.SettingsHandlers[handler_n].ClearAllFn)
13345
0
            g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
13346
0
}
13347
13348
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13349
0
{
13350
0
    size_t file_data_size = 0;
13351
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13352
0
    if (!file_data)
13353
0
        return;
13354
0
    if (file_data_size > 0)
13355
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13356
0
    IM_FREE(file_data);
13357
0
}
13358
13359
// Zero-tolerance, no error reporting, cheap .ini parsing
13360
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13361
0
{
13362
0
    ImGuiContext& g = *GImGui;
13363
0
    IM_ASSERT(g.Initialized);
13364
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13365
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13366
13367
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13368
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13369
0
    if (ini_size == 0)
13370
0
        ini_size = strlen(ini_data);
13371
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13372
0
    char* const buf = g.SettingsIniData.Buf.Data;
13373
0
    char* const buf_end = buf + ini_size;
13374
0
    memcpy(buf, ini_data, ini_size);
13375
0
    buf_end[0] = 0;
13376
13377
    // Call pre-read handlers
13378
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13379
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13380
0
        if (g.SettingsHandlers[handler_n].ReadInitFn)
13381
0
            g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
13382
13383
0
    void* entry_data = NULL;
13384
0
    ImGuiSettingsHandler* entry_handler = NULL;
13385
13386
0
    char* line_end = NULL;
13387
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13388
0
    {
13389
        // Skip new lines markers, then find end of the line
13390
0
        while (*line == '\n' || *line == '\r')
13391
0
            line++;
13392
0
        line_end = line;
13393
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13394
0
            line_end++;
13395
0
        line_end[0] = 0;
13396
0
        if (line[0] == ';')
13397
0
            continue;
13398
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13399
0
        {
13400
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13401
0
            line_end[-1] = 0;
13402
0
            const char* name_end = line_end - 1;
13403
0
            const char* type_start = line + 1;
13404
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13405
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13406
0
            if (!type_end || !name_start)
13407
0
                continue;
13408
0
            *type_end = 0; // Overwrite first ']'
13409
0
            name_start++;  // Skip second '['
13410
0
            entry_handler = FindSettingsHandler(type_start);
13411
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13412
0
        }
13413
0
        else if (entry_handler != NULL && entry_data != NULL)
13414
0
        {
13415
            // Let type handler parse the line
13416
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13417
0
        }
13418
0
    }
13419
0
    g.SettingsLoaded = true;
13420
13421
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13422
0
    memcpy(buf, ini_data, ini_size);
13423
13424
    // Call post-read handlers
13425
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13426
0
        if (g.SettingsHandlers[handler_n].ApplyAllFn)
13427
0
            g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
13428
0
}
13429
13430
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13431
0
{
13432
0
    ImGuiContext& g = *GImGui;
13433
0
    g.SettingsDirtyTimer = 0.0f;
13434
0
    if (!ini_filename)
13435
0
        return;
13436
13437
0
    size_t ini_data_size = 0;
13438
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13439
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13440
0
    if (!f)
13441
0
        return;
13442
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13443
0
    ImFileClose(f);
13444
0
}
13445
13446
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13447
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13448
0
{
13449
0
    ImGuiContext& g = *GImGui;
13450
0
    g.SettingsDirtyTimer = 0.0f;
13451
0
    g.SettingsIniData.Buf.resize(0);
13452
0
    g.SettingsIniData.Buf.push_back(0);
13453
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13454
0
    {
13455
0
        ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
13456
0
        handler->WriteAllFn(&g, handler, &g.SettingsIniData);
13457
0
    }
13458
0
    if (out_size)
13459
0
        *out_size = (size_t)g.SettingsIniData.size();
13460
0
    return g.SettingsIniData.c_str();
13461
0
}
13462
13463
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
13464
0
{
13465
0
    ImGuiContext& g = *GImGui;
13466
13467
0
#if !IMGUI_DEBUG_INI_SETTINGS
13468
    // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
13469
    // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
13470
0
    if (const char* p = strstr(name, "###"))
13471
0
        name = p;
13472
0
#endif
13473
0
    const size_t name_len = strlen(name);
13474
13475
    // Allocate chunk
13476
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
13477
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
13478
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
13479
0
    settings->ID = ImHashStr(name, name_len);
13480
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
13481
13482
0
    return settings;
13483
0
}
13484
13485
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
13486
// This is called once per window .ini entry + once per newly instantiated window.
13487
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
13488
2
{
13489
2
    ImGuiContext& g = *GImGui;
13490
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13491
0
        if (settings->ID == id)
13492
0
            return settings;
13493
2
    return NULL;
13494
2
}
13495
13496
// This is faster if you are holding on a Window already as we don't need to perform a search.
13497
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
13498
2
{
13499
2
    ImGuiContext& g = *GImGui;
13500
2
    if (window->SettingsOffset != -1)
13501
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
13502
2
    return FindWindowSettingsByID(window->ID);
13503
2
}
13504
13505
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
13506
void ImGui::ClearWindowSettings(const char* name)
13507
0
{
13508
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
13509
0
    ImGuiContext& g = *GImGui;
13510
0
    ImGuiWindow* window = FindWindowByName(name);
13511
0
    if (window != NULL)
13512
0
    {
13513
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
13514
0
        InitOrLoadWindowSettings(window, NULL);
13515
0
        if (window->DockId != 0)
13516
0
            DockContextProcessUndockWindow(&g, window, true);
13517
0
    }
13518
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
13519
0
        settings->WantDelete = true;
13520
0
}
13521
13522
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13523
0
{
13524
0
    ImGuiContext& g = *ctx;
13525
0
    for (int i = 0; i != g.Windows.Size; i++)
13526
0
        g.Windows[i]->SettingsOffset = -1;
13527
0
    g.SettingsWindows.clear();
13528
0
}
13529
13530
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
13531
0
{
13532
0
    ImGuiID id = ImHashStr(name);
13533
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
13534
0
    if (settings)
13535
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
13536
0
    else
13537
0
        settings = ImGui::CreateNewWindowSettings(name);
13538
0
    settings->ID = id;
13539
0
    settings->WantApply = true;
13540
0
    return (void*)settings;
13541
0
}
13542
13543
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
13544
0
{
13545
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
13546
0
    int x, y;
13547
0
    int i;
13548
0
    ImU32 u1;
13549
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
13550
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
13551
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
13552
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
13553
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
13554
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
13555
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
13556
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
13557
0
}
13558
13559
// Apply to existing windows (if any)
13560
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13561
0
{
13562
0
    ImGuiContext& g = *ctx;
13563
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13564
0
        if (settings->WantApply)
13565
0
        {
13566
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
13567
0
                ApplyWindowSettings(window, settings);
13568
0
            settings->WantApply = false;
13569
0
        }
13570
0
}
13571
13572
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
13573
0
{
13574
    // Gather data from windows that were active during this session
13575
    // (if a window wasn't opened in this session we preserve its settings)
13576
0
    ImGuiContext& g = *ctx;
13577
0
    for (int i = 0; i != g.Windows.Size; i++)
13578
0
    {
13579
0
        ImGuiWindow* window = g.Windows[i];
13580
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
13581
0
            continue;
13582
13583
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
13584
0
        if (!settings)
13585
0
        {
13586
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
13587
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
13588
0
        }
13589
0
        IM_ASSERT(settings->ID == window->ID);
13590
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
13591
0
        settings->Size = ImVec2ih(window->SizeFull);
13592
0
        settings->ViewportId = window->ViewportId;
13593
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
13594
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
13595
0
        settings->DockId = window->DockId;
13596
0
        settings->ClassId = window->WindowClass.ClassId;
13597
0
        settings->DockOrder = window->DockOrder;
13598
0
        settings->Collapsed = window->Collapsed;
13599
0
        settings->WantDelete = false;
13600
0
    }
13601
13602
    // Write to text buffer
13603
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
13604
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13605
0
    {
13606
0
        if (settings->WantDelete)
13607
0
            continue;
13608
0
        const char* settings_name = settings->GetName();
13609
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
13610
0
        if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13611
0
        {
13612
0
            buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
13613
0
            buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
13614
0
        }
13615
0
        if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13616
0
            buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
13617
0
        if (settings->Size.x != 0 || settings->Size.y != 0)
13618
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
13619
0
        buf->appendf("Collapsed=%d\n", settings->Collapsed);
13620
0
        if (settings->DockId != 0)
13621
0
        {
13622
            //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
13623
0
            if (settings->DockOrder == -1)
13624
0
                buf->appendf("DockId=0x%08X\n", settings->DockId);
13625
0
            else
13626
0
                buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
13627
0
            if (settings->ClassId != 0)
13628
0
                buf->appendf("ClassId=0x%08X\n", settings->ClassId);
13629
0
        }
13630
0
        buf->append("\n");
13631
0
    }
13632
0
}
13633
13634
13635
//-----------------------------------------------------------------------------
13636
// [SECTION] LOCALIZATION
13637
//-----------------------------------------------------------------------------
13638
13639
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
13640
1
{
13641
1
    ImGuiContext& g = *GImGui;
13642
9
    for (int n = 0; n < count; n++)
13643
8
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
13644
1
}
13645
13646
13647
//-----------------------------------------------------------------------------
13648
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
13649
//-----------------------------------------------------------------------------
13650
// - GetMainViewport()
13651
// - FindViewportByID()
13652
// - FindViewportByPlatformHandle()
13653
// - SetCurrentViewport() [Internal]
13654
// - SetWindowViewport() [Internal]
13655
// - GetWindowAlwaysWantOwnViewport() [Internal]
13656
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
13657
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
13658
// - TranslateWindowsInViewport() [Internal]
13659
// - ScaleWindowsInViewport() [Internal]
13660
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
13661
// - UpdateViewportsNewFrame() [Internal]
13662
// - UpdateViewportsEndFrame() [Internal]
13663
// - AddUpdateViewport() [Internal]
13664
// - WindowSelectViewport() [Internal]
13665
// - WindowSyncOwnedViewport() [Internal]
13666
// - UpdatePlatformWindows()
13667
// - RenderPlatformWindowsDefault()
13668
// - FindPlatformMonitorForPos() [Internal]
13669
// - FindPlatformMonitorForRect() [Internal]
13670
// - UpdateViewportPlatformMonitor() [Internal]
13671
// - DestroyPlatformWindow() [Internal]
13672
// - DestroyPlatformWindows()
13673
//-----------------------------------------------------------------------------
13674
13675
ImGuiViewport* ImGui::GetMainViewport()
13676
46.9k
{
13677
46.9k
    ImGuiContext& g = *GImGui;
13678
46.9k
    return g.Viewports[0];
13679
46.9k
}
13680
13681
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
13682
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
13683
21.3k
{
13684
21.3k
    ImGuiContext& g = *GImGui;
13685
21.3k
    for (int n = 0; n < g.Viewports.Size; n++)
13686
21.3k
        if (g.Viewports[n]->ID == id)
13687
21.3k
            return g.Viewports[n];
13688
0
    return NULL;
13689
21.3k
}
13690
13691
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
13692
0
{
13693
0
    ImGuiContext& g = *GImGui;
13694
0
    for (int i = 0; i != g.Viewports.Size; i++)
13695
0
        if (g.Viewports[i]->PlatformHandle == platform_handle)
13696
0
            return g.Viewports[i];
13697
0
    return NULL;
13698
0
}
13699
13700
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
13701
93.9k
{
13702
93.9k
    ImGuiContext& g = *GImGui;
13703
93.9k
    (void)current_window;
13704
13705
93.9k
    if (viewport)
13706
72.5k
        viewport->LastFrameActive = g.FrameCount;
13707
93.9k
    if (g.CurrentViewport == viewport)
13708
51.2k
        return;
13709
42.7k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
13710
42.7k
    g.CurrentViewport = viewport;
13711
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
13712
13713
    // Notify platform layer of viewport changes
13714
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
13715
42.7k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
13716
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
13717
42.7k
}
13718
13719
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13720
46.9k
{
13721
    // Abandon viewport
13722
46.9k
    if (window->ViewportOwned && window->Viewport->Window == window)
13723
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
13724
13725
46.9k
    window->Viewport = viewport;
13726
46.9k
    window->ViewportId = viewport->ID;
13727
46.9k
    window->ViewportOwned = (viewport->Window == window);
13728
46.9k
}
13729
13730
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
13731
0
{
13732
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
13733
0
    ImGuiContext& g = *GImGui;
13734
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
13735
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
13736
0
            if (!window->DockIsActive)
13737
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
13738
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
13739
0
                        return true;
13740
0
    return false;
13741
0
}
13742
13743
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13744
0
{
13745
0
    ImGuiContext& g = *GImGui;
13746
0
    if (window->Viewport == viewport)
13747
0
        return false;
13748
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
13749
0
        return false;
13750
0
    if ((viewport->Flags & ImGuiViewportFlags_Minimized) != 0)
13751
0
        return false;
13752
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
13753
0
        return false;
13754
0
    if (GetWindowAlwaysWantOwnViewport(window))
13755
0
        return false;
13756
13757
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
13758
0
    for (int n = 0; n < g.Windows.Size; n++)
13759
0
    {
13760
0
        ImGuiWindow* window_behind = g.Windows[n];
13761
0
        if (window_behind == window)
13762
0
            break;
13763
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
13764
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
13765
0
                return false;
13766
0
    }
13767
13768
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
13769
0
    ImGuiViewportP* old_viewport = window->Viewport;
13770
0
    if (window->ViewportOwned)
13771
0
        for (int n = 0; n < g.Windows.Size; n++)
13772
0
            if (g.Windows[n]->Viewport == old_viewport)
13773
0
                SetWindowViewport(g.Windows[n], viewport);
13774
0
    SetWindowViewport(window, viewport);
13775
0
    BringWindowToDisplayFront(window);
13776
13777
0
    return true;
13778
0
}
13779
13780
// FIXME: handle 0 to N host viewports
13781
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
13782
0
{
13783
0
    ImGuiContext& g = *GImGui;
13784
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
13785
0
}
13786
13787
// Translate Dear ImGui windows when a Host Viewport has been moved
13788
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13789
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
13790
0
{
13791
0
    ImGuiContext& g = *GImGui;
13792
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
13793
13794
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
13795
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
13796
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
13797
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
13798
    // and so the window will appear to teleport when releasing the mouse.
13799
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
13800
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
13801
0
    ImVec2 delta_pos = new_pos - old_pos;
13802
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
13803
0
        if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
13804
0
            TranslateWindow(g.Windows[window_n], delta_pos);
13805
0
}
13806
13807
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
13808
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
13809
0
{
13810
0
    ImGuiContext& g = *GImGui;
13811
0
    if (viewport->Window)
13812
0
    {
13813
0
        ScaleWindow(viewport->Window, scale);
13814
0
    }
13815
0
    else
13816
0
    {
13817
0
        for (int i = 0; i != g.Windows.Size; i++)
13818
0
            if (g.Windows[i]->Viewport == viewport)
13819
0
                ScaleWindow(g.Windows[i], scale);
13820
0
    }
13821
0
}
13822
13823
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
13824
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13825
// B) It requires Platform_GetWindowFocus to be implemented by backend.
13826
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
13827
0
{
13828
0
    ImGuiContext& g = *GImGui;
13829
0
    ImGuiViewportP* best_candidate = NULL;
13830
0
    for (int n = 0; n < g.Viewports.Size; n++)
13831
0
    {
13832
0
        ImGuiViewportP* viewport = g.Viewports[n];
13833
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
13834
0
            if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount)
13835
0
                best_candidate = viewport;
13836
0
    }
13837
0
    return best_candidate;
13838
0
}
13839
13840
// Update viewports and monitor infos
13841
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
13842
static void ImGui::UpdateViewportsNewFrame()
13843
21.3k
{
13844
21.3k
    ImGuiContext& g = *GImGui;
13845
21.3k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
13846
13847
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
13848
21.3k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
13849
21.3k
    if (viewports_enabled)
13850
0
    {
13851
0
        for (int n = 0; n < g.Viewports.Size; n++)
13852
0
        {
13853
0
            ImGuiViewportP* viewport = g.Viewports[n];
13854
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
13855
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
13856
0
            {
13857
0
                bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
13858
0
                if (minimized)
13859
0
                    viewport->Flags |= ImGuiViewportFlags_Minimized;
13860
0
                else
13861
0
                    viewport->Flags &= ~ImGuiViewportFlags_Minimized;
13862
0
            }
13863
0
        }
13864
0
    }
13865
13866
    // Create/update main viewport with current platform position.
13867
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
13868
21.3k
    ImGuiViewportP* main_viewport = g.Viewports[0];
13869
21.3k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
13870
21.3k
    IM_ASSERT(main_viewport->Window == NULL);
13871
21.3k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
13872
21.3k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
13873
21.3k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_Minimized))
13874
0
    {
13875
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
13876
0
        main_viewport_size = main_viewport->Size;
13877
0
    }
13878
21.3k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
13879
13880
21.3k
    g.CurrentDpiScale = 0.0f;
13881
21.3k
    g.CurrentViewport = NULL;
13882
21.3k
    g.MouseViewport = NULL;
13883
42.7k
    for (int n = 0; n < g.Viewports.Size; n++)
13884
21.3k
    {
13885
21.3k
        ImGuiViewportP* viewport = g.Viewports[n];
13886
21.3k
        viewport->Idx = n;
13887
13888
        // Erase unused viewports
13889
21.3k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
13890
0
        {
13891
0
            DestroyViewport(viewport);
13892
0
            n--;
13893
0
            continue;
13894
0
        }
13895
13896
21.3k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
13897
21.3k
        if (viewports_enabled)
13898
0
        {
13899
            // Update Position and Size (from Platform Window to ImGui) if requested.
13900
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
13901
0
            if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available)
13902
0
            {
13903
                // Viewport->WorkPos and WorkSize will be updated below
13904
0
                if (viewport->PlatformRequestMove)
13905
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
13906
0
                if (viewport->PlatformRequestResize)
13907
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
13908
0
            }
13909
0
        }
13910
13911
        // Update/copy monitor info
13912
21.3k
        UpdateViewportPlatformMonitor(viewport);
13913
13914
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
13915
21.3k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
13916
21.3k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
13917
21.3k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
13918
21.3k
        viewport->UpdateWorkRect();
13919
13920
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
13921
21.3k
        viewport->Alpha = 1.0f;
13922
13923
        // Translate Dear ImGui windows when a Host Viewport has been moved
13924
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13925
21.3k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
13926
21.3k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
13927
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
13928
13929
        // Update DPI scale
13930
21.3k
        float new_dpi_scale;
13931
21.3k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
13932
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
13933
21.3k
        else if (viewport->PlatformMonitor != -1)
13934
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
13935
21.3k
        else
13936
21.3k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
13937
21.3k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
13938
0
        {
13939
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
13940
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
13941
0
                ScaleWindowsInViewport(viewport, scale_factor);
13942
            //if (viewport == GetMainViewport())
13943
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
13944
13945
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
13946
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
13947
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
13948
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
13949
            //    g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
13950
0
        }
13951
21.3k
        viewport->DpiScale = new_dpi_scale;
13952
21.3k
    }
13953
13954
    // Update fallback monitor
13955
21.3k
    if (g.PlatformIO.Monitors.Size == 0)
13956
21.3k
    {
13957
21.3k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
13958
21.3k
        monitor->MainPos = main_viewport->Pos;
13959
21.3k
        monitor->MainSize = main_viewport->Size;
13960
21.3k
        monitor->WorkPos = main_viewport->WorkPos;
13961
21.3k
        monitor->WorkSize = main_viewport->WorkSize;
13962
21.3k
        monitor->DpiScale = main_viewport->DpiScale;
13963
21.3k
    }
13964
13965
21.3k
    if (!viewports_enabled)
13966
21.3k
    {
13967
21.3k
        g.MouseViewport = main_viewport;
13968
21.3k
        return;
13969
21.3k
    }
13970
13971
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
13972
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
13973
0
    ImGuiViewportP* viewport_hovered = NULL;
13974
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
13975
0
    {
13976
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
13977
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
13978
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
13979
0
    }
13980
0
    else
13981
0
    {
13982
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
13983
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13984
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
13985
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
13986
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
13987
0
    }
13988
0
    if (viewport_hovered != NULL)
13989
0
        g.MouseLastHoveredViewport = viewport_hovered;
13990
0
    else if (g.MouseLastHoveredViewport == NULL)
13991
0
        g.MouseLastHoveredViewport = g.Viewports[0];
13992
13993
    // Update mouse reference viewport
13994
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
13995
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
13996
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
13997
0
        g.MouseViewport = g.MovingWindow->Viewport;
13998
0
    else
13999
0
        g.MouseViewport = g.MouseLastHoveredViewport;
14000
14001
    // When dragging something, always refer to the last hovered viewport.
14002
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14003
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14004
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14005
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14006
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14007
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14008
0
        viewport_hovered = g.MouseLastHoveredViewport;
14009
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14010
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14011
0
            g.MouseViewport = viewport_hovered;
14012
14013
0
    IM_ASSERT(g.MouseViewport != NULL);
14014
0
}
14015
14016
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14017
static void ImGui::UpdateViewportsEndFrame()
14018
21.3k
{
14019
21.3k
    ImGuiContext& g = *GImGui;
14020
21.3k
    g.PlatformIO.Viewports.resize(0);
14021
42.7k
    for (int i = 0; i < g.Viewports.Size; i++)
14022
21.3k
    {
14023
21.3k
        ImGuiViewportP* viewport = g.Viewports[i];
14024
21.3k
        viewport->LastPos = viewport->Pos;
14025
21.3k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14026
0
            if (i > 0) // Always include main viewport in the list
14027
0
                continue;
14028
21.3k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
14029
0
            continue;
14030
21.3k
        if (i > 0)
14031
21.3k
            IM_ASSERT(viewport->Window != NULL);
14032
21.3k
        g.PlatformIO.Viewports.push_back(viewport);
14033
21.3k
    }
14034
21.3k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14035
21.3k
}
14036
14037
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14038
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14039
21.3k
{
14040
21.3k
    ImGuiContext& g = *GImGui;
14041
21.3k
    IM_ASSERT(id != 0);
14042
14043
21.3k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
14044
21.3k
    if (window != NULL)
14045
0
    {
14046
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14047
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14048
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14049
0
            flags |= ImGuiViewportFlags_NoInputs;
14050
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14051
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14052
0
    }
14053
14054
21.3k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
14055
21.3k
    if (viewport)
14056
21.3k
    {
14057
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
14058
21.3k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14059
21.3k
            viewport->Pos = pos;
14060
21.3k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14061
21.3k
            viewport->Size = size;
14062
21.3k
        viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags
14063
21.3k
    }
14064
0
    else
14065
0
    {
14066
        // New viewport
14067
0
        viewport = IM_NEW(ImGuiViewportP)();
14068
0
        viewport->ID = id;
14069
0
        viewport->Idx = g.Viewports.Size;
14070
0
        viewport->Pos = viewport->LastPos = pos;
14071
0
        viewport->Size = size;
14072
0
        viewport->Flags = flags;
14073
0
        UpdateViewportPlatformMonitor(viewport);
14074
0
        g.Viewports.push_back(viewport);
14075
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
14076
14077
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
14078
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
14079
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
14080
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
14081
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
14082
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
14083
14084
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
14085
        // This is so we can select an appropriate font size on the first frame of our window lifetime
14086
0
        if (viewport->PlatformMonitor != -1)
14087
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14088
0
    }
14089
14090
21.3k
    viewport->Window = window;
14091
21.3k
    viewport->LastFrameActive = g.FrameCount;
14092
21.3k
    viewport->UpdateWorkRect();
14093
21.3k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
14094
14095
21.3k
    if (window != NULL)
14096
0
        window->ViewportOwned = true;
14097
14098
21.3k
    return viewport;
14099
21.3k
}
14100
14101
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
14102
0
{
14103
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
14104
0
    ImGuiContext& g = *GImGui;
14105
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
14106
0
    {
14107
0
        ImGuiWindow* window = g.Windows[window_n];
14108
0
        if (window->Viewport != viewport)
14109
0
            continue;
14110
0
        window->Viewport = NULL;
14111
0
        window->ViewportOwned = false;
14112
0
    }
14113
0
    if (viewport == g.MouseLastHoveredViewport)
14114
0
        g.MouseLastHoveredViewport = NULL;
14115
14116
    // Destroy
14117
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14118
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
14119
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
14120
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
14121
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
14122
0
    IM_DELETE(viewport);
14123
0
}
14124
14125
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
14126
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
14127
46.9k
{
14128
46.9k
    ImGuiContext& g = *GImGui;
14129
46.9k
    ImGuiWindowFlags flags = window->Flags;
14130
46.9k
    window->ViewportAllowPlatformMonitorExtend = -1;
14131
14132
    // Restore main viewport if multi-viewport is not supported by the backend
14133
46.9k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
14134
46.9k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14135
46.9k
    {
14136
46.9k
        SetWindowViewport(window, main_viewport);
14137
46.9k
        return;
14138
46.9k
    }
14139
0
    window->ViewportOwned = false;
14140
14141
    // Appearing popups reset their viewport so they can inherit again
14142
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
14143
0
    {
14144
0
        window->Viewport = NULL;
14145
0
        window->ViewportId = 0;
14146
0
    }
14147
14148
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
14149
0
    {
14150
        // By default inherit from parent window
14151
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
14152
0
            window->Viewport = window->ParentWindow->Viewport;
14153
14154
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
14155
0
        if (window->Viewport == NULL && window->ViewportId != 0)
14156
0
        {
14157
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
14158
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
14159
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
14160
0
        }
14161
0
    }
14162
14163
0
    bool lock_viewport = false;
14164
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
14165
0
    {
14166
        // Code explicitly request a viewport
14167
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
14168
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
14169
0
        lock_viewport = true;
14170
0
    }
14171
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
14172
0
    {
14173
        // Always inherit viewport from parent window
14174
0
        if (window->DockNode && window->DockNode->HostWindow)
14175
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
14176
0
        window->Viewport = window->ParentWindow->Viewport;
14177
0
    }
14178
0
    else if (window->DockNode && window->DockNode->HostWindow)
14179
0
    {
14180
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
14181
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
14182
0
    }
14183
0
    else if (flags & ImGuiWindowFlags_Tooltip)
14184
0
    {
14185
0
        window->Viewport = g.MouseViewport;
14186
0
    }
14187
0
    else if (GetWindowAlwaysWantOwnViewport(window))
14188
0
    {
14189
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14190
0
    }
14191
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
14192
0
    {
14193
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
14194
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14195
0
    }
14196
0
    else
14197
0
    {
14198
        // Merge into host viewport?
14199
        // We cannot test window->ViewportOwned as it set lower in the function.
14200
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
14201
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
14202
0
        if (try_to_merge_into_host_viewport)
14203
0
            UpdateTryMergeWindowIntoHostViewports(window);
14204
0
    }
14205
14206
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
14207
0
    if (window->Viewport == NULL)
14208
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14209
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14210
14211
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14212
0
    if (!lock_viewport)
14213
0
    {
14214
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14215
0
        {
14216
            // We need to take account of the possibility that mouse may become invalid.
14217
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14218
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14219
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14220
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14221
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14222
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14223
0
            else
14224
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14225
0
        }
14226
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14227
0
        {
14228
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14229
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14230
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14231
0
            {
14232
                // Steal/transfer ownership
14233
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14234
0
                window->Viewport->Window = window;
14235
0
                window->Viewport->ID = window->ID;
14236
0
                window->Viewport->LastNameHash = 0;
14237
0
            }
14238
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14239
0
            {
14240
                // New viewport
14241
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14242
0
            }
14243
0
        }
14244
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14245
0
        {
14246
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14247
            // Child windows are kept contained within their parent.
14248
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14249
0
        }
14250
0
    }
14251
14252
    // Update flags
14253
0
    window->ViewportOwned = (window == window->Viewport->Window);
14254
0
    window->ViewportId = window->Viewport->ID;
14255
14256
    // If the OS window has a title bar, hide our imgui title bar
14257
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14258
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14259
0
}
14260
14261
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14262
0
{
14263
0
    ImGuiContext& g = *GImGui;
14264
14265
0
    bool viewport_rect_changed = false;
14266
14267
    // Synchronize window --> viewport in most situations
14268
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14269
0
    if (window->Viewport->PlatformRequestMove)
14270
0
    {
14271
0
        window->Pos = window->Viewport->Pos;
14272
0
        MarkIniSettingsDirty(window);
14273
0
    }
14274
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14275
0
    {
14276
0
        viewport_rect_changed = true;
14277
0
        window->Viewport->Pos = window->Pos;
14278
0
    }
14279
14280
0
    if (window->Viewport->PlatformRequestResize)
14281
0
    {
14282
0
        window->Size = window->SizeFull = window->Viewport->Size;
14283
0
        MarkIniSettingsDirty(window);
14284
0
    }
14285
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14286
0
    {
14287
0
        viewport_rect_changed = true;
14288
0
        window->Viewport->Size = window->Size;
14289
0
    }
14290
0
    window->Viewport->UpdateWorkRect();
14291
14292
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14293
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14294
0
    if (viewport_rect_changed)
14295
0
        UpdateViewportPlatformMonitor(window->Viewport);
14296
14297
    // Update common viewport flags
14298
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14299
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14300
0
    ImGuiWindowFlags window_flags = window->Flags;
14301
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14302
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14303
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14304
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14305
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14306
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14307
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14308
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14309
14310
    // Not correct to set modal as topmost because:
14311
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14312
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14313
    //if (flags & ImGuiWindowFlags_Modal)
14314
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14315
14316
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14317
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14318
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14319
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14320
0
    if (is_short_lived_floating_window && !is_modal)
14321
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14322
14323
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14324
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14325
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14326
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14327
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14328
14329
    // We can also tell the backend that clearing the platform window won't be necessary,
14330
    // as our window background is filling the viewport and we have disabled BgAlpha.
14331
    // FIXME: Work on support for per-viewport transparency (#2766)
14332
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14333
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14334
14335
0
    window->Viewport->Flags = viewport_flags;
14336
14337
    // Update parent viewport ID
14338
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14339
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14340
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14341
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14342
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14343
0
    else
14344
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14345
0
}
14346
14347
// Called by user at the end of the main loop, after EndFrame()
14348
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14349
void ImGui::UpdatePlatformWindows()
14350
0
{
14351
0
    ImGuiContext& g = *GImGui;
14352
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14353
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14354
0
    g.FrameCountPlatformEnded = g.FrameCount;
14355
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14356
0
        return;
14357
14358
    // Create/resize/destroy platform windows to match each active viewport.
14359
    // Skip the main viewport (index 0), which is always fully handled by the application!
14360
0
    for (int i = 1; i < g.Viewports.Size; i++)
14361
0
    {
14362
0
        ImGuiViewportP* viewport = g.Viewports[i];
14363
14364
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14365
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14366
0
        bool destroy_platform_window = false;
14367
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14368
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14369
0
        if (destroy_platform_window)
14370
0
        {
14371
0
            DestroyPlatformWindow(viewport);
14372
0
            continue;
14373
0
        }
14374
14375
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14376
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14377
0
            continue;
14378
14379
        // Create window
14380
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14381
0
        if (is_new_platform_window)
14382
0
        {
14383
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14384
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14385
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14386
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14387
0
            viewport->LastNameHash = 0;
14388
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14389
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14390
0
            viewport->PlatformWindowCreated = true;
14391
0
        }
14392
14393
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14394
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14395
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
14396
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
14397
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
14398
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
14399
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
14400
0
        viewport->LastPlatformPos = viewport->Pos;
14401
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
14402
14403
        // Update title bar (if it changed)
14404
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
14405
0
        {
14406
0
            const char* title_begin = window_for_title->Name;
14407
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
14408
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
14409
0
            if (viewport->LastNameHash != title_hash)
14410
0
            {
14411
0
                char title_end_backup_c = *title_end;
14412
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
14413
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
14414
0
                *title_end = title_end_backup_c;
14415
0
                viewport->LastNameHash = title_hash;
14416
0
            }
14417
0
        }
14418
14419
        // Update alpha (if it changed)
14420
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
14421
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
14422
0
        viewport->LastAlpha = viewport->Alpha;
14423
14424
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
14425
0
        if (g.PlatformIO.Platform_UpdateWindow)
14426
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
14427
14428
0
        if (is_new_platform_window)
14429
0
        {
14430
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
14431
0
            if (g.FrameCount < 3)
14432
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14433
14434
            // Show window
14435
0
            g.PlatformIO.Platform_ShowWindow(viewport);
14436
14437
            // Even without focus, we assume the window becomes front-most.
14438
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
14439
0
            if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
14440
0
                viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
14441
0
            }
14442
14443
        // Clear request flags
14444
0
        viewport->ClearRequestFlags();
14445
0
    }
14446
14447
    // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14448
    // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14449
    // FIXME-VIEWPORT: We should use this information to also set dear imgui-side focus, allowing us to handle os-level alt+tab.
14450
0
    if (g.PlatformIO.Platform_GetWindowFocus != NULL)
14451
0
    {
14452
0
        ImGuiViewportP* focused_viewport = NULL;
14453
0
        for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++)
14454
0
        {
14455
0
            ImGuiViewportP* viewport = g.Viewports[n];
14456
0
            if (viewport->PlatformWindowCreated)
14457
0
                if (g.PlatformIO.Platform_GetWindowFocus(viewport))
14458
0
                    focused_viewport = viewport;
14459
0
        }
14460
14461
        // Store a tag so we can infer z-order easily from all our windows
14462
        // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14463
        // will keep the front most stamp instead of losing it back to their parent viewport.
14464
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14465
0
        {
14466
0
            if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
14467
0
                focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
14468
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14469
0
        }
14470
0
    }
14471
0
}
14472
14473
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
14474
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
14475
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
14476
//
14477
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14478
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14479
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14480
//            MyRenderFunction(platform_io.Viewports[i], my_args);
14481
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14482
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14483
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
14484
//
14485
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
14486
0
{
14487
    // Skip the main viewport (index 0), which is always fully handled by the application!
14488
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14489
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14490
0
    {
14491
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14492
0
        if (viewport->Flags & ImGuiViewportFlags_Minimized)
14493
0
            continue;
14494
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
14495
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
14496
0
    }
14497
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14498
0
    {
14499
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14500
0
        if (viewport->Flags & ImGuiViewportFlags_Minimized)
14501
0
            continue;
14502
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
14503
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
14504
0
    }
14505
0
}
14506
14507
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
14508
0
{
14509
0
    ImGuiContext& g = *GImGui;
14510
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
14511
0
    {
14512
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14513
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
14514
0
            return monitor_n;
14515
0
    }
14516
0
    return -1;
14517
0
}
14518
14519
// Search for the monitor with the largest intersection area with the given rectangle
14520
// We generally try to avoid searching loops but the monitor count should be very small here
14521
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
14522
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
14523
21.3k
{
14524
21.3k
    ImGuiContext& g = *GImGui;
14525
14526
21.3k
    const int monitor_count = g.PlatformIO.Monitors.Size;
14527
21.3k
    if (monitor_count <= 1)
14528
21.3k
        return monitor_count - 1;
14529
14530
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
14531
    // This is necessary for tooltips which always resize down to zero at first.
14532
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
14533
0
    int best_monitor_n = -1;
14534
0
    float best_monitor_surface = 0.001f;
14535
14536
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
14537
0
    {
14538
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14539
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
14540
0
        if (monitor_rect.Contains(rect))
14541
0
            return monitor_n;
14542
0
        ImRect overlapping_rect = rect;
14543
0
        overlapping_rect.ClipWithFull(monitor_rect);
14544
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
14545
0
        if (overlapping_surface < best_monitor_surface)
14546
0
            continue;
14547
0
        best_monitor_surface = overlapping_surface;
14548
0
        best_monitor_n = monitor_n;
14549
0
    }
14550
0
    return best_monitor_n;
14551
0
}
14552
14553
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
14554
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
14555
21.3k
{
14556
21.3k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
14557
21.3k
}
14558
14559
// Return value is always != NULL, but don't hold on it across frames.
14560
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
14561
0
{
14562
0
    ImGuiContext& g = *GImGui;
14563
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
14564
0
    int monitor_idx = viewport->PlatformMonitor;
14565
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
14566
0
        return &g.PlatformIO.Monitors[monitor_idx];
14567
0
    return &g.FallbackMonitor;
14568
0
}
14569
14570
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
14571
0
{
14572
0
    ImGuiContext& g = *GImGui;
14573
0
    if (viewport->PlatformWindowCreated)
14574
0
    {
14575
0
        if (g.PlatformIO.Renderer_DestroyWindow)
14576
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
14577
0
        if (g.PlatformIO.Platform_DestroyWindow)
14578
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
14579
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
14580
14581
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
14582
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
14583
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
14584
0
            viewport->PlatformWindowCreated = false;
14585
0
    }
14586
0
    else
14587
0
    {
14588
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
14589
0
    }
14590
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
14591
0
    viewport->ClearRequestFlags();
14592
0
}
14593
14594
void ImGui::DestroyPlatformWindows()
14595
0
{
14596
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
14597
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
14598
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
14599
    // code to operator a consistent manner.
14600
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
14601
    // crashing if it doesn't have data stored.
14602
0
    ImGuiContext& g = *GImGui;
14603
0
    for (int i = 0; i < g.Viewports.Size; i++)
14604
0
        DestroyPlatformWindow(g.Viewports[i]);
14605
0
}
14606
14607
14608
//-----------------------------------------------------------------------------
14609
// [SECTION] DOCKING
14610
//-----------------------------------------------------------------------------
14611
// Docking: Internal Types
14612
// Docking: Forward Declarations
14613
// Docking: ImGuiDockContext
14614
// Docking: ImGuiDockContext Docking/Undocking functions
14615
// Docking: ImGuiDockNode
14616
// Docking: ImGuiDockNode Tree manipulation functions
14617
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
14618
// Docking: Builder Functions
14619
// Docking: Begin/End Support Functions (called from Begin/End)
14620
// Docking: Settings
14621
//-----------------------------------------------------------------------------
14622
14623
//-----------------------------------------------------------------------------
14624
// Typical Docking call flow: (root level is generally public API):
14625
//-----------------------------------------------------------------------------
14626
// - NewFrame()                               new dear imgui frame
14627
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
14628
//    | - DockContextProcessUndockWindow()    - process one window undocking request
14629
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
14630
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
14631
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
14632
//    | - DockContextProcessDock()            - process one docking request
14633
//    | - DockNodeUpdate()
14634
//    |   - DockNodeUpdateForRootNode()
14635
//    |     - DockNodeUpdateFlagsAndCollapse()
14636
//    |     - DockNodeFindInfo()
14637
//    |   - destroy unused node or tab bar
14638
//    |   - create dock node host window
14639
//    |      - Begin() etc.
14640
//    |   - DockNodeStartMouseMovingWindow()
14641
//    |   - DockNodeTreeUpdatePosSize()
14642
//    |   - DockNodeTreeUpdateSplitter()
14643
//    |   - draw node background
14644
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
14645
//    |     - DockNodeAddTabBar()
14646
//    |     - DockNodeUpdateWindowMenu()
14647
//    |     - DockNodeCalcTabBarLayout()
14648
//    |     - BeginTabBarEx()
14649
//    |     - TabItemEx() calls
14650
//    |     - EndTabBar()
14651
//    |   - BeginDockableDragDropTarget()
14652
//    |      - DockNodeUpdate()               - recurse into child nodes...
14653
//-----------------------------------------------------------------------------
14654
// - DockSpace()                              user submit a dockspace into a window
14655
//    | Begin(Child)                          - create a child window
14656
//    | DockNodeUpdate()                      - call main dock node update function
14657
//    | End(Child)
14658
//    | ItemSize()
14659
//-----------------------------------------------------------------------------
14660
// - Begin()
14661
//    | BeginDocked()
14662
//    | BeginDockableDragDropSource()
14663
//    | BeginDockableDragDropTarget()
14664
//    | - DockNodePreviewDockRender()
14665
//-----------------------------------------------------------------------------
14666
// - EndFrame()
14667
//    | DockContextEndFrame()
14668
//-----------------------------------------------------------------------------
14669
14670
//-----------------------------------------------------------------------------
14671
// Docking: Internal Types
14672
//-----------------------------------------------------------------------------
14673
// - ImGuiDockRequestType
14674
// - ImGuiDockRequest
14675
// - ImGuiDockPreviewData
14676
// - ImGuiDockNodeSettings
14677
// - ImGuiDockContext
14678
//-----------------------------------------------------------------------------
14679
14680
enum ImGuiDockRequestType
14681
{
14682
    ImGuiDockRequestType_None = 0,
14683
    ImGuiDockRequestType_Dock,
14684
    ImGuiDockRequestType_Undock,
14685
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
14686
};
14687
14688
struct ImGuiDockRequest
14689
{
14690
    ImGuiDockRequestType    Type;
14691
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
14692
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
14693
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
14694
    ImGuiDir                DockSplitDir;
14695
    float                   DockSplitRatio;
14696
    bool                    DockSplitOuter;
14697
    ImGuiWindow*            UndockTargetWindow;
14698
    ImGuiDockNode*          UndockTargetNode;
14699
14700
    ImGuiDockRequest()
14701
0
    {
14702
0
        Type = ImGuiDockRequestType_None;
14703
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
14704
0
        DockTargetNode = UndockTargetNode = NULL;
14705
0
        DockSplitDir = ImGuiDir_None;
14706
0
        DockSplitRatio = 0.5f;
14707
0
        DockSplitOuter = false;
14708
0
    }
14709
};
14710
14711
struct ImGuiDockPreviewData
14712
{
14713
    ImGuiDockNode   FutureNode;
14714
    bool            IsDropAllowed;
14715
    bool            IsCenterAvailable;
14716
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
14717
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
14718
    ImGuiDockNode*  SplitNode;
14719
    ImGuiDir        SplitDir;
14720
    float           SplitRatio;
14721
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
14722
14723
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
14724
};
14725
14726
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
14727
struct ImGuiDockNodeSettings
14728
{
14729
    ImGuiID             ID;
14730
    ImGuiID             ParentNodeId;
14731
    ImGuiID             ParentWindowId;
14732
    ImGuiID             SelectedTabId;
14733
    signed char         SplitAxis;
14734
    char                Depth;
14735
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
14736
    ImVec2ih            Pos;
14737
    ImVec2ih            Size;
14738
    ImVec2ih            SizeRef;
14739
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
14740
};
14741
14742
//-----------------------------------------------------------------------------
14743
// Docking: Forward Declarations
14744
//-----------------------------------------------------------------------------
14745
14746
namespace ImGui
14747
{
14748
    // ImGuiDockContext
14749
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
14750
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
14751
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
14752
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
14753
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
14754
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
14755
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
14756
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
14757
14758
    // ImGuiDockNode
14759
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
14760
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14761
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14762
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
14763
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
14764
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
14765
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
14766
    static void             DockNodeUpdate(ImGuiDockNode* node);
14767
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
14768
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
14769
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
14770
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
14771
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
14772
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
14773
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
14774
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
14775
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
14776
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
14777
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
14778
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
14779
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
14780
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
14781
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
14782
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
14783
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
14784
14785
    // ImGuiDockNode tree manipulations
14786
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
14787
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
14788
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
14789
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
14790
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
14791
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
14792
14793
    // Settings
14794
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
14795
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
14796
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
14797
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
14798
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
14799
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
14800
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
14801
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
14802
}
14803
14804
//-----------------------------------------------------------------------------
14805
// Docking: ImGuiDockContext
14806
//-----------------------------------------------------------------------------
14807
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
14808
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
14809
// At boot time only, we run a simple GC to remove nodes that have no references.
14810
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
14811
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
14812
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
14813
//-----------------------------------------------------------------------------
14814
// - DockContextInitialize()
14815
// - DockContextShutdown()
14816
// - DockContextClearNodes()
14817
// - DockContextRebuildNodes()
14818
// - DockContextNewFrameUpdateUndocking()
14819
// - DockContextNewFrameUpdateDocking()
14820
// - DockContextEndFrame()
14821
// - DockContextFindNodeByID()
14822
// - DockContextBindNodeToWindow()
14823
// - DockContextGenNodeID()
14824
// - DockContextAddNode()
14825
// - DockContextRemoveNode()
14826
// - ImGuiDockContextPruneNodeData
14827
// - DockContextPruneUnusedSettingsNodes()
14828
// - DockContextBuildNodesFromSettings()
14829
// - DockContextBuildAddWindowsToNodes()
14830
//-----------------------------------------------------------------------------
14831
14832
void ImGui::DockContextInitialize(ImGuiContext* ctx)
14833
1
{
14834
1
    ImGuiContext& g = *ctx;
14835
14836
    // Add .ini handle for persistent docking data
14837
1
    ImGuiSettingsHandler ini_handler;
14838
1
    ini_handler.TypeName = "Docking";
14839
1
    ini_handler.TypeHash = ImHashStr("Docking");
14840
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
14841
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
14842
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
14843
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
14844
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
14845
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
14846
1
    g.SettingsHandlers.push_back(ini_handler);
14847
14848
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
14849
1
}
14850
14851
void ImGui::DockContextShutdown(ImGuiContext* ctx)
14852
0
{
14853
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14854
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14855
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14856
0
            IM_DELETE(node);
14857
0
}
14858
14859
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
14860
0
{
14861
0
    IM_UNUSED(ctx);
14862
0
    IM_ASSERT(ctx == GImGui);
14863
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
14864
0
    DockBuilderRemoveNodeChildNodes(root_id);
14865
0
}
14866
14867
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
14868
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
14869
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
14870
0
{
14871
0
    ImGuiContext& g = *ctx;
14872
0
    ImGuiDockContext* dc = &ctx->DockContext;
14873
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
14874
0
    SaveIniSettingsToMemory();
14875
0
    ImGuiID root_id = 0; // Rebuild all
14876
0
    DockContextClearNodes(ctx, root_id, false);
14877
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
14878
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
14879
0
}
14880
14881
// Docking context update function, called by NewFrame()
14882
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
14883
21.3k
{
14884
21.3k
    ImGuiContext& g = *ctx;
14885
21.3k
    ImGuiDockContext* dc = &ctx->DockContext;
14886
21.3k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
14887
0
    {
14888
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
14889
0
            DockContextClearNodes(ctx, 0, true);
14890
0
        return;
14891
0
    }
14892
14893
    // Setting NoSplit at runtime merges all nodes
14894
21.3k
    if (g.IO.ConfigDockingNoSplit)
14895
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
14896
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14897
0
                if (node->IsRootNode() && node->IsSplitNode())
14898
0
                {
14899
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
14900
                    //dc->WantFullRebuild = true;
14901
0
                }
14902
14903
    // Process full rebuild
14904
#if 0
14905
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
14906
        dc->WantFullRebuild = true;
14907
#endif
14908
21.3k
    if (dc->WantFullRebuild)
14909
0
    {
14910
0
        DockContextRebuildNodes(ctx);
14911
0
        dc->WantFullRebuild = false;
14912
0
    }
14913
14914
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
14915
21.3k
    for (int n = 0; n < dc->Requests.Size; n++)
14916
0
    {
14917
0
        ImGuiDockRequest* req = &dc->Requests[n];
14918
0
        if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
14919
0
            DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
14920
0
        else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
14921
0
            DockContextProcessUndockNode(ctx, req->UndockTargetNode);
14922
0
    }
14923
21.3k
}
14924
14925
// Docking context update function, called by NewFrame()
14926
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
14927
21.3k
{
14928
21.3k
    ImGuiContext& g = *ctx;
14929
21.3k
    ImGuiDockContext* dc  = &ctx->DockContext;
14930
21.3k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
14931
0
        return;
14932
14933
    // [DEBUG] Store hovered dock node.
14934
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
14935
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
14936
21.3k
    g.DebugHoveredDockNode = NULL;
14937
21.3k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
14938
1.10k
    {
14939
1.10k
        if (hovered_window->DockNodeAsHost)
14940
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
14941
1.10k
        else if (hovered_window->RootWindow->DockNode)
14942
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
14943
1.10k
    }
14944
14945
    // Process Docking requests
14946
21.3k
    for (int n = 0; n < dc->Requests.Size; n++)
14947
0
        if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
14948
0
            DockContextProcessDock(ctx, &dc->Requests[n]);
14949
21.3k
    dc->Requests.resize(0);
14950
14951
    // Create windows for each automatic docking nodes
14952
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
14953
21.3k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14954
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14955
0
            if (node->IsFloatingNode())
14956
0
                DockNodeUpdate(node);
14957
21.3k
}
14958
14959
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
14960
21.3k
{
14961
    // Draw backgrounds of node missing their window
14962
21.3k
    ImGuiContext& g = *ctx;
14963
21.3k
    ImGuiDockContext* dc = &g.DockContext;
14964
21.3k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14965
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14966
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
14967
0
            {
14968
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
14969
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), DOCKING_SPLITTER_SIZE);
14970
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
14971
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
14972
0
            }
14973
21.3k
}
14974
14975
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
14976
0
{
14977
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
14978
0
}
14979
14980
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
14981
0
{
14982
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
14983
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
14984
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
14985
0
    ImGuiID id = 0x0001;
14986
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
14987
0
        id++;
14988
0
    return id;
14989
0
}
14990
14991
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
14992
0
{
14993
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
14994
0
    ImGuiContext& g = *ctx;
14995
0
    if (id == 0)
14996
0
        id = DockContextGenNodeID(ctx);
14997
0
    else
14998
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
14999
15000
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15001
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15002
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15003
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15004
0
    return node;
15005
0
}
15006
15007
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15008
0
{
15009
0
    ImGuiContext& g = *ctx;
15010
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15011
15012
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15013
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15014
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15015
0
    IM_ASSERT(node->Windows.Size == 0);
15016
15017
0
    if (node->HostWindow)
15018
0
        node->HostWindow->DockNodeAsHost = NULL;
15019
15020
0
    ImGuiDockNode* parent_node = node->ParentNode;
15021
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15022
0
    if (merge)
15023
0
    {
15024
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15025
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15026
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
15027
0
    }
15028
0
    else
15029
0
    {
15030
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15031
0
            if (parent_node->ChildNodes[n] == node)
15032
0
                node->ParentNode->ChildNodes[n] = NULL;
15033
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
15034
0
        IM_DELETE(node);
15035
0
    }
15036
0
}
15037
15038
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15039
0
{
15040
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15041
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15042
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15043
0
}
15044
15045
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15046
struct ImGuiDockContextPruneNodeData
15047
{
15048
    int         CountWindows, CountChildWindows, CountChildNodes;
15049
    ImGuiID     RootId;
15050
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
15051
};
15052
15053
// Garbage collect unused nodes (run once at init time)
15054
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15055
0
{
15056
0
    ImGuiContext& g = *ctx;
15057
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15058
0
    IM_ASSERT(g.Windows.Size == 0);
15059
15060
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
15061
0
    pool.Reserve(dc->NodesSettings.Size);
15062
15063
    // Count child nodes and compute RootID
15064
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15065
0
    {
15066
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15067
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
15068
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15069
0
        if (settings->ParentNodeId)
15070
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
15071
0
    }
15072
15073
    // Count reference to dock ids from dockspaces
15074
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
15075
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15076
0
    {
15077
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15078
0
        if (settings->ParentWindowId != 0)
15079
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
15080
0
                if (window_settings->DockId)
15081
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
15082
0
                        data->CountChildNodes++;
15083
0
    }
15084
15085
    // Count reference to dock ids from window settings
15086
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
15087
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15088
0
        if (ImGuiID dock_id = settings->DockId)
15089
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
15090
0
            {
15091
0
                data->CountWindows++;
15092
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
15093
0
                    data_root->CountChildWindows++;
15094
0
            }
15095
15096
    // Prune
15097
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15098
0
    {
15099
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15100
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
15101
0
        if (data->CountWindows > 1)
15102
0
            continue;
15103
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
15104
15105
0
        bool remove = false;
15106
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
15107
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
15108
0
        remove |= (data_root->CountChildWindows == 0);
15109
0
        if (remove)
15110
0
        {
15111
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
15112
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
15113
0
            settings->ID = 0;
15114
0
        }
15115
0
    }
15116
0
}
15117
15118
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
15119
0
{
15120
    // Build nodes
15121
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
15122
0
    {
15123
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
15124
0
        if (settings->ID == 0)
15125
0
            continue;
15126
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
15127
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
15128
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
15129
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
15130
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
15131
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
15132
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
15133
0
            node->ParentNode->ChildNodes[0] = node;
15134
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
15135
0
            node->ParentNode->ChildNodes[1] = node;
15136
0
        node->SelectedTabId = settings->SelectedTabId;
15137
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
15138
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
15139
15140
        // Bind host window immediately if it already exist (in case of a rebuild)
15141
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
15142
0
        char host_window_title[20];
15143
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
15144
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
15145
0
    }
15146
0
}
15147
15148
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
15149
0
{
15150
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
15151
0
    ImGuiContext& g = *ctx;
15152
0
    for (int n = 0; n < g.Windows.Size; n++)
15153
0
    {
15154
0
        ImGuiWindow* window = g.Windows[n];
15155
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
15156
0
            continue;
15157
0
        if (window->DockNode != NULL)
15158
0
            continue;
15159
15160
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
15161
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
15162
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
15163
0
            DockNodeAddWindow(node, window, true);
15164
0
    }
15165
0
}
15166
15167
//-----------------------------------------------------------------------------
15168
// Docking: ImGuiDockContext Docking/Undocking functions
15169
//-----------------------------------------------------------------------------
15170
// - DockContextQueueDock()
15171
// - DockContextQueueUndockWindow()
15172
// - DockContextQueueUndockNode()
15173
// - DockContextQueueNotifyRemovedNode()
15174
// - DockContextProcessDock()
15175
// - DockContextProcessUndockWindow()
15176
// - DockContextProcessUndockNode()
15177
// - DockContextCalcDropPosForDocking()
15178
//-----------------------------------------------------------------------------
15179
15180
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
15181
0
{
15182
0
    IM_ASSERT(target != payload);
15183
0
    ImGuiDockRequest req;
15184
0
    req.Type = ImGuiDockRequestType_Dock;
15185
0
    req.DockTargetWindow = target;
15186
0
    req.DockTargetNode = target_node;
15187
0
    req.DockPayload = payload;
15188
0
    req.DockSplitDir = split_dir;
15189
0
    req.DockSplitRatio = split_ratio;
15190
0
    req.DockSplitOuter = split_outer;
15191
0
    ctx->DockContext.Requests.push_back(req);
15192
0
}
15193
15194
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
15195
0
{
15196
0
    ImGuiDockRequest req;
15197
0
    req.Type = ImGuiDockRequestType_Undock;
15198
0
    req.UndockTargetWindow = window;
15199
0
    ctx->DockContext.Requests.push_back(req);
15200
0
}
15201
15202
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15203
0
{
15204
0
    ImGuiDockRequest req;
15205
0
    req.Type = ImGuiDockRequestType_Undock;
15206
0
    req.UndockTargetNode = node;
15207
0
    ctx->DockContext.Requests.push_back(req);
15208
0
}
15209
15210
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15211
0
{
15212
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15213
0
    for (int n = 0; n < dc->Requests.Size; n++)
15214
0
        if (dc->Requests[n].DockTargetNode == node)
15215
0
            dc->Requests[n].Type = ImGuiDockRequestType_None;
15216
0
}
15217
15218
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15219
0
{
15220
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15221
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15222
15223
0
    ImGuiContext& g = *ctx;
15224
0
    IM_UNUSED(g);
15225
15226
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15227
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15228
0
    ImGuiDockNode* node = req->DockTargetNode;
15229
0
    if (payload_window)
15230
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15231
0
    else
15232
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15233
15234
    // Decide which Tab will be selected at the end of the operation
15235
0
    ImGuiID next_selected_id = 0;
15236
0
    ImGuiDockNode* payload_node = NULL;
15237
0
    if (payload_window)
15238
0
    {
15239
0
        payload_node = payload_window->DockNodeAsHost;
15240
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15241
0
        if (payload_node && payload_node->IsLeafNode())
15242
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15243
0
        if (payload_node == NULL)
15244
0
            next_selected_id = payload_window->TabId;
15245
0
    }
15246
15247
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15248
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15249
0
    if (node)
15250
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15251
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15252
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15253
15254
    // Create new node and add existing window to it
15255
0
    if (node == NULL)
15256
0
    {
15257
0
        node = DockContextAddNode(ctx, 0);
15258
0
        node->Pos = target_window->Pos;
15259
0
        node->Size = target_window->Size;
15260
0
        if (target_window->DockNodeAsHost == NULL)
15261
0
        {
15262
0
            DockNodeAddWindow(node, target_window, true);
15263
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15264
0
            target_window->DockIsActive = true;
15265
0
        }
15266
0
    }
15267
15268
0
    ImGuiDir split_dir = req->DockSplitDir;
15269
0
    if (split_dir != ImGuiDir_None)
15270
0
    {
15271
        // Split into two, one side will be our payload node unless we are dropping a loose window
15272
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15273
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15274
0
        const float split_ratio = req->DockSplitRatio;
15275
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15276
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15277
0
        new_node->HostWindow = node->HostWindow;
15278
0
        node = new_node;
15279
0
    }
15280
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15281
15282
0
    if (node != payload_node)
15283
0
    {
15284
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15285
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15286
0
        {
15287
0
            DockNodeAddTabBar(node);
15288
0
            for (int n = 0; n < node->Windows.Size; n++)
15289
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15290
0
        }
15291
15292
0
        if (payload_node != NULL)
15293
0
        {
15294
            // Transfer full payload node (with 1+ child windows or child nodes)
15295
0
            if (payload_node->IsSplitNode())
15296
0
            {
15297
0
                if (node->Windows.Size > 0)
15298
0
                {
15299
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15300
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15301
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15302
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15303
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15304
0
                    if (visible_node->TabBar)
15305
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15306
0
                    DockNodeMoveWindows(node, visible_node);
15307
0
                    DockNodeMoveWindows(visible_node, node);
15308
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15309
0
                }
15310
0
                if (node->IsCentralNode())
15311
0
                {
15312
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15313
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15314
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15315
0
                    IM_ASSERT(last_focused_node != NULL);
15316
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15317
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15318
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15319
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15320
0
                    last_focused_root_node->CentralNode = last_focused_node;
15321
0
                }
15322
15323
0
                IM_ASSERT(node->Windows.Size == 0);
15324
0
                DockNodeMoveChildNodes(node, payload_node);
15325
0
            }
15326
0
            else
15327
0
            {
15328
0
                const ImGuiID payload_dock_id = payload_node->ID;
15329
0
                DockNodeMoveWindows(node, payload_node);
15330
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15331
0
            }
15332
0
            DockContextRemoveNode(ctx, payload_node, true);
15333
0
        }
15334
0
        else if (payload_window)
15335
0
        {
15336
            // Transfer single window
15337
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15338
0
            node->VisibleWindow = payload_window;
15339
0
            DockNodeAddWindow(node, payload_window, true);
15340
0
            if (payload_dock_id != 0)
15341
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15342
0
        }
15343
0
    }
15344
0
    else
15345
0
    {
15346
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15347
0
        node->WantHiddenTabBarUpdate = true;
15348
0
    }
15349
15350
    // Update selection immediately
15351
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15352
0
        tab_bar->NextSelectedTabId = next_selected_id;
15353
0
    MarkIniSettingsDirty();
15354
0
}
15355
15356
// Problem:
15357
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15358
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15359
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15360
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15361
// Solution:
15362
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15363
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15364
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15365
0
{
15366
0
    if (ref_viewport == NULL)
15367
0
        return size;
15368
15369
0
    ImGuiContext& g = *GImGui;
15370
0
    ImVec2 max_size = ImFloor(ref_viewport->WorkSize * 0.90f);
15371
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15372
0
    {
15373
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15374
0
        max_size = ImFloor(monitor->WorkSize * 0.90f);
15375
0
    }
15376
0
    return ImMin(size, max_size);
15377
0
}
15378
15379
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15380
0
{
15381
0
    ImGuiContext& g = *ctx;
15382
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15383
0
    if (window->DockNode)
15384
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15385
0
    else
15386
0
        window->DockId = 0;
15387
0
    window->Collapsed = false;
15388
0
    window->DockIsActive = false;
15389
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15390
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15391
15392
0
    MarkIniSettingsDirty();
15393
0
}
15394
15395
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15396
0
{
15397
0
    ImGuiContext& g = *ctx;
15398
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15399
0
    IM_ASSERT(node->IsLeafNode());
15400
0
    IM_ASSERT(node->Windows.Size >= 1);
15401
15402
0
    if (node->IsRootNode() || node->IsCentralNode())
15403
0
    {
15404
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15405
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15406
0
        new_node->Pos = node->Pos;
15407
0
        new_node->Size = node->Size;
15408
0
        new_node->SizeRef = node->SizeRef;
15409
0
        DockNodeMoveWindows(new_node, node);
15410
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15411
0
        node = new_node;
15412
0
    }
15413
0
    else
15414
0
    {
15415
        // Otherwise extract our node and merge our sibling back into the parent node.
15416
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15417
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15418
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15419
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15420
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15421
0
        node->ParentNode = NULL;
15422
0
    }
15423
0
    for (int n = 0; n < node->Windows.Size; n++)
15424
0
    {
15425
0
        ImGuiWindow* window = node->Windows[n];
15426
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15427
0
        if (window->ParentWindow)
15428
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
15429
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
15430
0
    }
15431
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
15432
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
15433
0
    node->WantMouseMove = true;
15434
0
    MarkIniSettingsDirty();
15435
0
}
15436
15437
// This is mostly used for automation.
15438
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
15439
0
{
15440
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
15441
    // (which would be functionally identical) we only show the outer one. Reflect this here.
15442
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
15443
0
        split_outer = true;
15444
0
    ImGuiDockPreviewData split_data;
15445
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
15446
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
15447
0
        return false;
15448
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
15449
0
    return true;
15450
0
}
15451
15452
//-----------------------------------------------------------------------------
15453
// Docking: ImGuiDockNode
15454
//-----------------------------------------------------------------------------
15455
// - DockNodeGetTabOrder()
15456
// - DockNodeAddWindow()
15457
// - DockNodeRemoveWindow()
15458
// - DockNodeMoveChildNodes()
15459
// - DockNodeMoveWindows()
15460
// - DockNodeApplyPosSizeToWindows()
15461
// - DockNodeHideHostWindow()
15462
// - ImGuiDockNodeFindInfoResults
15463
// - DockNodeFindInfo()
15464
// - DockNodeFindWindowByID()
15465
// - DockNodeUpdateFlagsAndCollapse()
15466
// - DockNodeUpdateHasCentralNodeFlag()
15467
// - DockNodeUpdateVisibleFlag()
15468
// - DockNodeStartMouseMovingWindow()
15469
// - DockNodeUpdate()
15470
// - DockNodeUpdateWindowMenu()
15471
// - DockNodeBeginAmendTabBar()
15472
// - DockNodeEndAmendTabBar()
15473
// - DockNodeUpdateTabBar()
15474
// - DockNodeAddTabBar()
15475
// - DockNodeRemoveTabBar()
15476
// - DockNodeIsDropAllowedOne()
15477
// - DockNodeIsDropAllowed()
15478
// - DockNodeCalcTabBarLayout()
15479
// - DockNodeCalcSplitRects()
15480
// - DockNodeCalcDropRectsAndTestMousePos()
15481
// - DockNodePreviewDockSetup()
15482
// - DockNodePreviewDockRender()
15483
//-----------------------------------------------------------------------------
15484
15485
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
15486
0
{
15487
0
    ID = id;
15488
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
15489
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
15490
0
    TabBar = NULL;
15491
0
    SplitAxis = ImGuiAxis_None;
15492
15493
0
    State = ImGuiDockNodeState_Unknown;
15494
0
    LastBgColor = IM_COL32_WHITE;
15495
0
    HostWindow = VisibleWindow = NULL;
15496
0
    CentralNode = OnlyNodeWithWindows = NULL;
15497
0
    CountNodeWithWindows = 0;
15498
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
15499
0
    LastFocusedNodeId = 0;
15500
0
    SelectedTabId = 0;
15501
0
    WantCloseTabId = 0;
15502
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
15503
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
15504
0
    IsVisible = true;
15505
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
15506
0
    IsBgDrawnThisFrame = false;
15507
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
15508
0
}
15509
15510
ImGuiDockNode::~ImGuiDockNode()
15511
0
{
15512
0
    IM_DELETE(TabBar);
15513
0
    TabBar = NULL;
15514
0
    ChildNodes[0] = ChildNodes[1] = NULL;
15515
0
}
15516
15517
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
15518
0
{
15519
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
15520
0
    if (tab_bar == NULL)
15521
0
        return -1;
15522
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
15523
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
15524
0
}
15525
15526
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
15527
0
{
15528
0
    window->Hidden = true;
15529
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
15530
0
}
15531
15532
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
15533
0
{
15534
0
    ImGuiContext& g = *GImGui; (void)g;
15535
0
    if (window->DockNode)
15536
0
    {
15537
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
15538
0
        IM_ASSERT(window->DockNode->ID != node->ID);
15539
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
15540
0
    }
15541
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
15542
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15543
15544
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
15545
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
15546
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
15547
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
15548
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
15549
15550
0
    node->Windows.push_back(window);
15551
0
    node->WantHiddenTabBarUpdate = true;
15552
0
    window->DockNode = node;
15553
0
    window->DockId = node->ID;
15554
0
    window->DockIsActive = (node->Windows.Size > 1);
15555
0
    window->DockTabWantClose = false;
15556
15557
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
15558
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
15559
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
15560
0
    {
15561
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
15562
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
15563
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
15564
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
15565
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
15566
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
15567
0
    }
15568
15569
    // Add to tab bar if requested
15570
0
    if (add_to_tab_bar)
15571
0
    {
15572
0
        if (node->TabBar == NULL)
15573
0
        {
15574
0
            DockNodeAddTabBar(node);
15575
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
15576
15577
            // Add existing windows
15578
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
15579
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15580
0
        }
15581
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
15582
0
    }
15583
15584
0
    DockNodeUpdateVisibleFlag(node);
15585
15586
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
15587
0
    if (node->HostWindow)
15588
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
15589
0
}
15590
15591
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
15592
0
{
15593
0
    ImGuiContext& g = *GImGui;
15594
0
    IM_ASSERT(window->DockNode == node);
15595
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
15596
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
15597
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
15598
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15599
15600
0
    window->DockNode = NULL;
15601
0
    window->DockIsActive = window->DockTabWantClose = false;
15602
0
    window->DockId = save_dock_id;
15603
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15604
0
    if (window->ParentWindow)
15605
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
15606
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
15607
15608
    // Remove window
15609
0
    bool erased = false;
15610
0
    for (int n = 0; n < node->Windows.Size; n++)
15611
0
        if (node->Windows[n] == window)
15612
0
        {
15613
0
            node->Windows.erase(node->Windows.Data + n);
15614
0
            erased = true;
15615
0
            break;
15616
0
        }
15617
0
    if (!erased)
15618
0
        IM_ASSERT(erased);
15619
0
    if (node->VisibleWindow == window)
15620
0
        node->VisibleWindow = NULL;
15621
15622
    // Remove tab and possibly tab bar
15623
0
    node->WantHiddenTabBarUpdate = true;
15624
0
    if (node->TabBar)
15625
0
    {
15626
0
        TabBarRemoveTab(node->TabBar, window->TabId);
15627
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
15628
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
15629
0
            DockNodeRemoveTabBar(node);
15630
0
    }
15631
15632
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
15633
0
    {
15634
        // Automatic dock node delete themselves if they are not holding at least one tab
15635
0
        DockContextRemoveNode(&g, node, true);
15636
0
        return;
15637
0
    }
15638
15639
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
15640
0
    {
15641
0
        ImGuiWindow* remaining_window = node->Windows[0];
15642
0
        if (node->HostWindow->ViewportOwned && node->IsRootNode())
15643
0
        {
15644
            // Transfer viewport back to the remaining loose window
15645
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X=>%08X for Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, remaining_window->ID, remaining_window->Name);
15646
0
            IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
15647
0
            node->HostWindow->Viewport->Window = remaining_window;
15648
0
            node->HostWindow->Viewport->ID = remaining_window->ID;
15649
0
        }
15650
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
15651
0
    }
15652
15653
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
15654
0
    DockNodeUpdateVisibleFlag(node);
15655
0
}
15656
15657
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15658
0
{
15659
0
    IM_ASSERT(dst_node->Windows.Size == 0);
15660
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
15661
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
15662
0
    if (dst_node->ChildNodes[0])
15663
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
15664
0
    if (dst_node->ChildNodes[1])
15665
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
15666
0
    dst_node->SplitAxis = src_node->SplitAxis;
15667
0
    dst_node->SizeRef = src_node->SizeRef;
15668
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
15669
0
}
15670
15671
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15672
0
{
15673
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
15674
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
15675
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
15676
0
    if (src_tab_bar != NULL)
15677
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
15678
15679
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
15680
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
15681
0
    if (move_tab_bar)
15682
0
    {
15683
0
        dst_node->TabBar = src_node->TabBar;
15684
0
        src_node->TabBar = NULL;
15685
0
    }
15686
15687
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
15688
0
    for (ImGuiWindow* window : src_node->Windows)
15689
0
    {
15690
0
        window->DockNode = NULL;
15691
0
        window->DockIsActive = false;
15692
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
15693
0
    }
15694
0
    src_node->Windows.clear();
15695
15696
0
    if (!move_tab_bar && src_node->TabBar)
15697
0
    {
15698
0
        if (dst_node->TabBar)
15699
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
15700
0
        DockNodeRemoveTabBar(src_node);
15701
0
    }
15702
0
}
15703
15704
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
15705
0
{
15706
0
    for (int n = 0; n < node->Windows.Size; n++)
15707
0
    {
15708
0
        SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
15709
0
        SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
15710
0
    }
15711
0
}
15712
15713
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
15714
0
{
15715
0
    if (node->HostWindow)
15716
0
    {
15717
0
        if (node->HostWindow->DockNodeAsHost == node)
15718
0
            node->HostWindow->DockNodeAsHost = NULL;
15719
0
        node->HostWindow = NULL;
15720
0
    }
15721
15722
0
    if (node->Windows.Size == 1)
15723
0
    {
15724
0
        node->VisibleWindow = node->Windows[0];
15725
0
        node->Windows[0]->DockIsActive = false;
15726
0
    }
15727
15728
0
    if (node->TabBar)
15729
0
        DockNodeRemoveTabBar(node);
15730
0
}
15731
15732
// Search function called once by root node in DockNodeUpdate()
15733
struct ImGuiDockNodeTreeInfo
15734
{
15735
    ImGuiDockNode*      CentralNode;
15736
    ImGuiDockNode*      FirstNodeWithWindows;
15737
    int                 CountNodesWithWindows;
15738
    //ImGuiWindowClass  WindowClassForMerges;
15739
15740
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
15741
};
15742
15743
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
15744
0
{
15745
0
    if (node->Windows.Size > 0)
15746
0
    {
15747
0
        if (info->FirstNodeWithWindows == NULL)
15748
0
            info->FirstNodeWithWindows = node;
15749
0
        info->CountNodesWithWindows++;
15750
0
    }
15751
0
    if (node->IsCentralNode())
15752
0
    {
15753
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
15754
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
15755
0
        info->CentralNode = node;
15756
0
    }
15757
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
15758
0
        return;
15759
0
    if (node->ChildNodes[0])
15760
0
        DockNodeFindInfo(node->ChildNodes[0], info);
15761
0
    if (node->ChildNodes[1])
15762
0
        DockNodeFindInfo(node->ChildNodes[1], info);
15763
0
}
15764
15765
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
15766
0
{
15767
0
    IM_ASSERT(id != 0);
15768
0
    for (int n = 0; n < node->Windows.Size; n++)
15769
0
        if (node->Windows[n]->ID == id)
15770
0
            return node->Windows[n];
15771
0
    return NULL;
15772
0
}
15773
15774
// - Remove inactive windows/nodes.
15775
// - Update visibility flag.
15776
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
15777
0
{
15778
0
    ImGuiContext& g = *GImGui;
15779
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15780
15781
    // Inherit most flags
15782
0
    if (node->ParentNode)
15783
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
15784
15785
    // Recurse into children
15786
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
15787
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
15788
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
15789
0
    node->HasCentralNodeChild = false;
15790
0
    if (node->ChildNodes[0])
15791
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
15792
0
    if (node->ChildNodes[1])
15793
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
15794
15795
    // Remove inactive windows, collapse nodes
15796
    // Merge node flags overrides stored in windows
15797
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
15798
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15799
0
    {
15800
0
        ImGuiWindow* window = node->Windows[window_n];
15801
0
        IM_ASSERT(window->DockNode == node);
15802
15803
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
15804
0
        bool remove = false;
15805
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
15806
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
15807
0
        remove |= (window->DockTabWantClose);
15808
0
        if (remove)
15809
0
        {
15810
0
            window->DockTabWantClose = false;
15811
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
15812
0
            {
15813
0
                DockNodeHideHostWindow(node);
15814
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15815
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
15816
0
                return;
15817
0
            }
15818
0
            DockNodeRemoveWindow(node, window, node->ID);
15819
0
            window_n--;
15820
0
            continue;
15821
0
        }
15822
15823
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
15824
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
15825
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
15826
0
    }
15827
0
    node->UpdateMergedFlags();
15828
15829
    // Auto-hide tab bar option
15830
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
15831
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
15832
0
        node->WantHiddenTabBarToggle = true;
15833
0
    node->WantHiddenTabBarUpdate = false;
15834
15835
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
15836
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
15837
0
        node->WantHiddenTabBarToggle = false;
15838
15839
    // Apply toggles at a single point of the frame (here!)
15840
0
    if (node->Windows.Size > 1)
15841
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15842
0
    else if (node->WantHiddenTabBarToggle)
15843
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
15844
0
    node->WantHiddenTabBarToggle = false;
15845
15846
0
    DockNodeUpdateVisibleFlag(node);
15847
0
}
15848
15849
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
15850
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
15851
0
{
15852
0
    node->HasCentralNodeChild = false;
15853
0
    if (node->ChildNodes[0])
15854
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
15855
0
    if (node->ChildNodes[1])
15856
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
15857
0
    if (node->IsRootNode())
15858
0
    {
15859
0
        ImGuiDockNode* mark_node = node->CentralNode;
15860
0
        while (mark_node)
15861
0
        {
15862
0
            mark_node->HasCentralNodeChild = true;
15863
0
            mark_node = mark_node->ParentNode;
15864
0
        }
15865
0
    }
15866
0
}
15867
15868
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
15869
0
{
15870
    // Update visibility flag
15871
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
15872
0
    is_visible |= (node->Windows.Size > 0);
15873
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
15874
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
15875
0
    node->IsVisible = is_visible;
15876
0
}
15877
15878
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
15879
0
{
15880
0
    ImGuiContext& g = *GImGui;
15881
0
    IM_ASSERT(node->WantMouseMove == true);
15882
0
    StartMouseMovingWindow(window);
15883
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
15884
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
15885
0
    node->WantMouseMove = false;
15886
0
}
15887
15888
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
15889
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
15890
0
{
15891
0
    DockNodeUpdateFlagsAndCollapse(node);
15892
15893
    // - Setup central node pointers
15894
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
15895
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
15896
0
    ImGuiDockNodeTreeInfo info;
15897
0
    DockNodeFindInfo(node, &info);
15898
0
    node->CentralNode = info.CentralNode;
15899
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
15900
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
15901
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
15902
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
15903
15904
    // Copy the window class from of our first window so it can be used for proper dock filtering.
15905
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
15906
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
15907
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
15908
0
    {
15909
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
15910
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
15911
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
15912
0
            {
15913
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
15914
0
                break;
15915
0
            }
15916
0
    }
15917
15918
0
    ImGuiDockNode* mark_node = node->CentralNode;
15919
0
    while (mark_node)
15920
0
    {
15921
0
        mark_node->HasCentralNodeChild = true;
15922
0
        mark_node = mark_node->ParentNode;
15923
0
    }
15924
0
}
15925
15926
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
15927
0
{
15928
    // Remove ourselves from any previous different host window
15929
    // This can happen if a user mistakenly does (see #4295 for details):
15930
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
15931
    //  - N+1: NewFrame()                   // will create floating host window for that node
15932
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
15933
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
15934
0
        node->HostWindow->DockNodeAsHost = NULL;
15935
15936
0
    host_window->DockNodeAsHost = node;
15937
0
    node->HostWindow = host_window;
15938
0
}
15939
15940
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
15941
0
{
15942
0
    ImGuiContext& g = *GImGui;
15943
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
15944
0
    node->LastFrameAlive = g.FrameCount;
15945
0
    node->IsBgDrawnThisFrame = false;
15946
15947
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
15948
0
    if (node->IsRootNode())
15949
0
        DockNodeUpdateForRootNode(node);
15950
15951
    // Remove tab bar if not needed
15952
0
    if (node->TabBar && node->IsNoTabBar())
15953
0
        DockNodeRemoveTabBar(node);
15954
15955
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
15956
0
    bool want_to_hide_host_window = false;
15957
0
    if (node->IsFloatingNode())
15958
0
    {
15959
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
15960
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
15961
0
                want_to_hide_host_window = true;
15962
0
        if (node->CountNodeWithWindows == 0)
15963
0
            want_to_hide_host_window = true;
15964
0
    }
15965
0
    if (want_to_hide_host_window)
15966
0
    {
15967
0
        if (node->Windows.Size == 1)
15968
0
        {
15969
            // Floating window pos/size is authoritative
15970
0
            ImGuiWindow* single_window = node->Windows[0];
15971
0
            node->Pos = single_window->Pos;
15972
0
            node->Size = single_window->SizeFull;
15973
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
15974
15975
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
15976
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
15977
0
                FocusWindow(single_window);
15978
0
            if (node->HostWindow)
15979
0
            {
15980
0
                single_window->Viewport = node->HostWindow->Viewport;
15981
0
                single_window->ViewportId = node->HostWindow->ViewportId;
15982
0
                if (node->HostWindow->ViewportOwned)
15983
0
                {
15984
0
                    single_window->Viewport->Window = single_window;
15985
0
                    single_window->ViewportOwned = true;
15986
0
                }
15987
0
            }
15988
0
        }
15989
15990
0
        DockNodeHideHostWindow(node);
15991
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15992
0
        node->WantCloseAll = false;
15993
0
        node->WantCloseTabId = 0;
15994
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
15995
0
        node->LastFrameActive = g.FrameCount;
15996
15997
0
        if (node->WantMouseMove && node->Windows.Size == 1)
15998
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
15999
0
        return;
16000
0
    }
16001
16002
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16003
    // while the expected visible window is resizing itself.
16004
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16005
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16006
    //   N+0: Begin(): window created (with no known size), node is created
16007
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16008
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16009
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16010
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16011
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
16012
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16013
0
    {
16014
0
        IM_ASSERT(node->Windows.Size > 0);
16015
0
        ImGuiWindow* ref_window = NULL;
16016
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16017
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16018
0
        if (ref_window == NULL)
16019
0
            ref_window = node->Windows[0];
16020
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16021
0
        {
16022
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16023
0
            return;
16024
0
        }
16025
0
    }
16026
16027
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16028
16029
    // Decide if the node will have a close button and a window menu button
16030
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16031
0
    node->HasCloseButton = false;
16032
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16033
0
    {
16034
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16035
0
        ImGuiWindow* window = node->Windows[window_n];
16036
0
        node->HasCloseButton |= window->HasCloseButton;
16037
0
        window->DockIsActive = (node->Windows.Size > 1);
16038
0
    }
16039
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16040
0
        node->HasCloseButton = false;
16041
16042
    // Bind or create host window
16043
0
    ImGuiWindow* host_window = NULL;
16044
0
    bool beginned_into_host_window = false;
16045
0
    if (node->IsDockSpace())
16046
0
    {
16047
        // [Explicit root dockspace node]
16048
0
        IM_ASSERT(node->HostWindow);
16049
0
        host_window = node->HostWindow;
16050
0
    }
16051
0
    else
16052
0
    {
16053
        // [Automatic root or child nodes]
16054
0
        if (node->IsRootNode() && node->IsVisible)
16055
0
        {
16056
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16057
16058
            // Sync Pos
16059
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16060
0
                SetNextWindowPos(ref_window->Pos);
16061
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16062
0
                SetNextWindowPos(node->Pos);
16063
16064
            // Sync Size
16065
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16066
0
                SetNextWindowSize(ref_window->SizeFull);
16067
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
16068
0
                SetNextWindowSize(node->Size);
16069
16070
            // Sync Collapsed
16071
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16072
0
                SetNextWindowCollapsed(ref_window->Collapsed);
16073
16074
            // Sync Viewport
16075
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
16076
0
                SetNextWindowViewport(ref_window->ViewportId);
16077
16078
0
            SetNextWindowClass(&node->WindowClass);
16079
16080
            // Begin into the host window
16081
0
            char window_label[20];
16082
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
16083
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
16084
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
16085
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
16086
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
16087
16088
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
16089
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
16090
0
            Begin(window_label, NULL, window_flags);
16091
0
            PopStyleVar();
16092
0
            beginned_into_host_window = true;
16093
16094
0
            host_window = g.CurrentWindow;
16095
0
            DockNodeSetupHostWindow(node, host_window);
16096
0
            host_window->DC.CursorPos = host_window->Pos;
16097
0
            node->Pos = host_window->Pos;
16098
0
            node->Size = host_window->Size;
16099
16100
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
16101
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
16102
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
16103
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
16104
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
16105
            // after the dock host window, losing their top-most status.
16106
0
            if (node->HostWindow->Appearing)
16107
0
                BringWindowToDisplayFront(node->HostWindow);
16108
16109
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16110
0
        }
16111
0
        else if (node->ParentNode)
16112
0
        {
16113
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
16114
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16115
0
        }
16116
0
        if (node->WantMouseMove && node->HostWindow)
16117
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
16118
0
    }
16119
16120
    // Update focused node (the one whose title bar is highlight) within a node tree
16121
0
    if (node->IsSplitNode())
16122
0
        IM_ASSERT(node->TabBar == NULL);
16123
0
    if (node->IsRootNode())
16124
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
16125
0
            while (p_window != NULL && p_window->DockNode != NULL)
16126
0
            {
16127
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
16128
0
                if (p_node == node)
16129
0
                {
16130
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
16131
0
                    break;
16132
0
                }
16133
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
16134
0
            }
16135
16136
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
16137
0
    ImGuiDockNode* central_node = node->CentralNode;
16138
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
16139
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
16140
0
    if (central_node_hole)
16141
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
16142
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
16143
0
                central_node_hole_register_hit_test_hole = false;
16144
0
    if (central_node_hole_register_hit_test_hole)
16145
0
    {
16146
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
16147
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
16148
        // covering passthru node we'd have a gap on the edge not covered by the hole)
16149
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
16150
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
16151
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
16152
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
16153
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
16154
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
16155
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
16156
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
16157
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
16158
0
        if (central_node_hole && !hole_rect.IsInverted())
16159
0
        {
16160
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16161
0
            if (host_window->ParentWindow)
16162
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16163
0
        }
16164
0
    }
16165
16166
    // Update position/size, process and draw resizing splitters
16167
0
    if (node->IsRootNode() && host_window)
16168
0
    {
16169
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
16170
0
        DockNodeTreeUpdateSplitter(node);
16171
0
    }
16172
16173
    // Draw empty node background (currently can only be the Central Node)
16174
0
    if (host_window && node->IsEmpty() && node->IsVisible)
16175
0
    {
16176
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16177
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
16178
0
        if (node->LastBgColor != 0)
16179
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
16180
0
        node->IsBgDrawnThisFrame = true;
16181
0
    }
16182
16183
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
16184
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
16185
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
16186
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
16187
0
    if (render_dockspace_bg && node->IsVisible)
16188
0
    {
16189
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16190
0
        if (central_node_hole)
16191
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
16192
0
        else
16193
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
16194
0
    }
16195
16196
    // Draw and populate Tab Bar
16197
0
    if (host_window)
16198
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
16199
0
    if (host_window && node->Windows.Size > 0)
16200
0
    {
16201
0
        DockNodeUpdateTabBar(node, host_window);
16202
0
    }
16203
0
    else
16204
0
    {
16205
0
        node->WantCloseAll = false;
16206
0
        node->WantCloseTabId = 0;
16207
0
        node->IsFocused = false;
16208
0
    }
16209
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16210
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16211
0
    else if (node->Windows.Size > 0)
16212
0
        node->SelectedTabId = node->Windows[0]->TabId;
16213
16214
    // Draw payload drop target
16215
0
    if (host_window && node->IsVisible)
16216
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16217
0
            BeginDockableDragDropTarget(host_window);
16218
16219
    // We update this after DockNodeUpdateTabBar()
16220
0
    node->LastFrameActive = g.FrameCount;
16221
16222
    // Recurse into children
16223
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16224
0
    if (host_window)
16225
0
    {
16226
0
        if (node->ChildNodes[0])
16227
0
            DockNodeUpdate(node->ChildNodes[0]);
16228
0
        if (node->ChildNodes[1])
16229
0
            DockNodeUpdate(node->ChildNodes[1]);
16230
16231
        // Render outer borders last (after the tab bar)
16232
0
        if (node->IsRootNode())
16233
0
            RenderWindowOuterBorders(host_window);
16234
0
    }
16235
16236
    // End host window
16237
0
    if (beginned_into_host_window) //-V1020
16238
0
        End();
16239
0
}
16240
16241
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16242
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16243
0
{
16244
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16245
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16246
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16247
0
        return d;
16248
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16249
0
}
16250
16251
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
16252
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
16253
// Custom overrides may want to decorate, group, sort entries.
16254
// Please note those are internal structures: if you copy this expect occasional breakage.
16255
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16256
0
{
16257
0
    IM_UNUSED(ctx);
16258
0
    if (tab_bar->Tabs.Size == 1)
16259
0
    {
16260
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
16261
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16262
0
            node->WantHiddenTabBarToggle = true;
16263
0
    }
16264
0
    else
16265
0
    {
16266
        // Display a selectable list of windows in this docking node
16267
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16268
0
        {
16269
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16270
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
16271
0
                continue;
16272
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
16273
0
                TabBarQueueFocus(tab_bar, tab);
16274
0
            SameLine();
16275
0
            Text("   ");
16276
0
        }
16277
0
    }
16278
0
}
16279
16280
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16281
0
{
16282
    // Try to position the menu so it is more likely to stays within the same viewport
16283
0
    ImGuiContext& g = *GImGui;
16284
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16285
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16286
0
    else
16287
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16288
0
    if (BeginPopup("#WindowMenu"))
16289
0
    {
16290
0
        node->IsFocused = true;
16291
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
16292
0
        EndPopup();
16293
0
    }
16294
0
}
16295
16296
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16297
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16298
0
{
16299
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16300
0
        return false;
16301
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16302
0
        return false;
16303
0
    Begin(node->HostWindow->Name);
16304
0
    PushOverrideID(node->ID);
16305
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node);
16306
0
    IM_UNUSED(ret);
16307
0
    IM_ASSERT(ret);
16308
0
    return true;
16309
0
}
16310
16311
void ImGui::DockNodeEndAmendTabBar()
16312
0
{
16313
0
    EndTabBar();
16314
0
    PopID();
16315
0
    End();
16316
0
}
16317
16318
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16319
0
{
16320
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16321
0
    ImGuiContext& g = *GImGui;
16322
0
    if (g.NavWindowingTarget)
16323
0
        return (g.NavWindowingTarget->DockNode == node);
16324
16325
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16326
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16327
0
    {
16328
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16329
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16330
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16331
0
            parent_window = parent_window->ParentWindow->RootWindow;
16332
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16333
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16334
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16335
0
                return true;
16336
0
    }
16337
0
    return false;
16338
0
}
16339
16340
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16341
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16342
0
{
16343
0
    ImGuiContext& g = *GImGui;
16344
0
    ImGuiStyle& style = g.Style;
16345
16346
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16347
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16348
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16349
0
    node->WantCloseAll = false;
16350
0
    node->WantCloseTabId = 0;
16351
16352
    // Decide if we should use a focused title bar color
16353
0
    bool is_focused = false;
16354
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16355
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16356
0
        is_focused = true;
16357
16358
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16359
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16360
0
    {
16361
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16362
0
        node->IsFocused = is_focused;
16363
0
        if (is_focused)
16364
0
            node->LastFrameFocused = g.FrameCount;
16365
0
        if (node->VisibleWindow)
16366
0
        {
16367
            // Notify root of visible window (used to display title in OS task bar)
16368
0
            if (is_focused || root_node->VisibleWindow == NULL)
16369
0
                root_node->VisibleWindow = node->VisibleWindow;
16370
0
            if (node->TabBar)
16371
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16372
0
        }
16373
0
        return;
16374
0
    }
16375
16376
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16377
0
    bool backup_skip_item = host_window->SkipItems;
16378
0
    if (!node->IsDockSpace())
16379
0
    {
16380
0
        host_window->SkipItems = false;
16381
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16382
0
    }
16383
16384
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16385
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16386
    // as docked windows themselves will override the stack with their own root ID.
16387
0
    PushOverrideID(node->ID);
16388
0
    ImGuiTabBar* tab_bar = node->TabBar;
16389
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16390
0
    if (tab_bar == NULL)
16391
0
    {
16392
0
        DockNodeAddTabBar(node);
16393
0
        tab_bar = node->TabBar;
16394
0
    }
16395
16396
0
    ImGuiID focus_tab_id = 0;
16397
0
    node->IsFocused = is_focused;
16398
16399
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16400
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16401
16402
    // In a dock node, the Collapse Button turns into the Window Menu button.
16403
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
16404
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
16405
0
    {
16406
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
16407
0
        DockNodeWindowMenuUpdate(node, tab_bar);
16408
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
16409
0
            focus_tab_id = tab_bar->NextSelectedTabId;
16410
0
        is_focused |= node->IsFocused;
16411
0
    }
16412
16413
    // Layout
16414
0
    ImRect title_bar_rect, tab_bar_rect;
16415
0
    ImVec2 window_menu_button_pos;
16416
0
    ImVec2 close_button_pos;
16417
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
16418
16419
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
16420
0
    const int tabs_count_old = tab_bar->Tabs.Size;
16421
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16422
0
    {
16423
0
        ImGuiWindow* window = node->Windows[window_n];
16424
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
16425
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
16426
0
    }
16427
16428
    // Title bar
16429
0
    if (is_focused)
16430
0
        node->LastFrameFocused = g.FrameCount;
16431
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
16432
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE);
16433
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
16434
16435
    // Docking/Collapse button
16436
0
    if (has_window_menu_button)
16437
0
    {
16438
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
16439
0
            OpenPopup("#WindowMenu");
16440
0
        if (IsItemActive())
16441
0
            focus_tab_id = tab_bar->SelectedTabId;
16442
0
    }
16443
16444
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
16445
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
16446
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
16447
0
    {
16448
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
16449
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
16450
0
        tabs_unsorted_start = tab_n;
16451
0
    }
16452
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
16453
0
    {
16454
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
16455
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
16456
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
16457
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
16458
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
16459
0
    }
16460
16461
    // Apply NavWindow focus back to the tab bar
16462
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
16463
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
16464
16465
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
16466
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
16467
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
16468
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
16469
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
16470
16471
    // Begin tab bar
16472
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
16473
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
16474
0
    if (!host_window->Collapsed && is_focused)
16475
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
16476
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
16477
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
16478
16479
    // Backup style colors
16480
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
16481
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16482
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
16483
16484
    // Submit actual tabs
16485
0
    node->VisibleWindow = NULL;
16486
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16487
0
    {
16488
0
        ImGuiWindow* window = node->Windows[window_n];
16489
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
16490
0
            continue;
16491
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
16492
0
        {
16493
0
            ImGuiTabItemFlags tab_item_flags = 0;
16494
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
16495
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
16496
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
16497
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
16498
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
16499
16500
            // Apply stored style overrides for the window
16501
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16502
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
16503
16504
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
16505
0
            bool tab_open = true;
16506
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
16507
0
            if (!tab_open)
16508
0
                node->WantCloseTabId = window->TabId;
16509
0
            if (tab_bar->VisibleTabId == window->TabId)
16510
0
                node->VisibleWindow = window;
16511
16512
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
16513
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
16514
0
            window->DockTabItemRect = g.LastItemData.Rect;
16515
16516
            // Update navigation ID on menu layer
16517
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
16518
0
                host_window->NavLastIds[1] = window->TabId;
16519
0
        }
16520
0
    }
16521
16522
    // Restore style colors
16523
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16524
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
16525
16526
    // Notify root of visible window (used to display title in OS task bar)
16527
0
    if (node->VisibleWindow)
16528
0
        if (is_focused || root_node->VisibleWindow == NULL)
16529
0
            root_node->VisibleWindow = node->VisibleWindow;
16530
16531
    // Close button (after VisibleWindow was updated)
16532
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
16533
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
16534
0
    const bool close_button_is_visible = node->HasCloseButton;
16535
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
16536
0
    if (close_button_is_visible)
16537
0
    {
16538
0
        if (!close_button_is_enabled)
16539
0
        {
16540
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
16541
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
16542
0
        }
16543
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
16544
0
        {
16545
0
            node->WantCloseAll = true;
16546
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
16547
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
16548
0
        }
16549
        //if (IsItemActive())
16550
        //    focus_tab_id = tab_bar->SelectedTabId;
16551
0
        if (!close_button_is_enabled)
16552
0
        {
16553
0
            PopStyleColor();
16554
0
            PopItemFlag();
16555
0
        }
16556
0
    }
16557
16558
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
16559
    // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held)
16560
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
16561
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
16562
0
    {
16563
0
        bool held;
16564
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap);
16565
0
        if (g.HoveredId == title_bar_id)
16566
0
        {
16567
            // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar,
16568
            // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
16569
0
            g.LastItemData.ID = title_bar_id;
16570
0
            SetItemAllowOverlap();
16571
0
        }
16572
0
        if (held)
16573
0
        {
16574
0
            if (IsMouseClicked(0))
16575
0
                focus_tab_id = tab_bar->SelectedTabId;
16576
16577
            // Forward moving request to selected window
16578
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
16579
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false);
16580
0
        }
16581
0
    }
16582
16583
    // Forward focus from host node to selected window
16584
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
16585
    //    focus_tab_id = tab_bar->SelectedTabId;
16586
16587
    // When clicked on a tab we requested focus to the docked child
16588
    // This overrides the value set by "forward focus from host node to selected window".
16589
0
    if (tab_bar->NextSelectedTabId)
16590
0
        focus_tab_id = tab_bar->NextSelectedTabId;
16591
16592
    // Apply navigation focus
16593
0
    if (focus_tab_id != 0)
16594
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
16595
0
            if (tab->Window)
16596
0
            {
16597
0
                FocusWindow(tab->Window);
16598
0
                NavInitWindow(tab->Window, false);
16599
0
            }
16600
16601
0
    EndTabBar();
16602
0
    PopID();
16603
16604
    // Restore SkipItems flag
16605
0
    if (!node->IsDockSpace())
16606
0
    {
16607
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
16608
0
        host_window->SkipItems = backup_skip_item;
16609
0
    }
16610
0
}
16611
16612
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
16613
0
{
16614
0
    IM_ASSERT(node->TabBar == NULL);
16615
0
    node->TabBar = IM_NEW(ImGuiTabBar);
16616
0
}
16617
16618
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
16619
0
{
16620
0
    if (node->TabBar == NULL)
16621
0
        return;
16622
0
    IM_DELETE(node->TabBar);
16623
0
    node->TabBar = NULL;
16624
0
}
16625
16626
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
16627
0
{
16628
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
16629
0
        return false;
16630
16631
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
16632
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
16633
0
    if (host_class->ClassId != payload_class->ClassId)
16634
0
    {
16635
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
16636
0
            return true;
16637
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
16638
0
            return true;
16639
0
        return false;
16640
0
    }
16641
16642
    // Prevent docking any window created above a popup
16643
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
16644
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
16645
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
16646
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
16647
0
    ImGuiContext& g = *GImGui;
16648
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
16649
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
16650
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
16651
0
                return false;
16652
16653
0
    return true;
16654
0
}
16655
16656
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
16657
0
{
16658
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
16659
0
        return true;
16660
16661
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
16662
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
16663
0
    {
16664
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
16665
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
16666
0
            return true;
16667
0
    }
16668
0
    return false;
16669
0
}
16670
16671
// window menu button == collapse button when not in a dock node.
16672
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
16673
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
16674
0
{
16675
0
    ImGuiContext& g = *GImGui;
16676
0
    ImGuiStyle& style = g.Style;
16677
16678
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
16679
0
    if (out_title_rect) { *out_title_rect = r; }
16680
16681
0
    r.Min.x += style.WindowBorderSize;
16682
0
    r.Max.x -= style.WindowBorderSize;
16683
16684
0
    float button_sz = g.FontSize;
16685
16686
0
    ImVec2 window_menu_button_pos = r.Min;
16687
0
    r.Min.x += style.FramePadding.x;
16688
0
    r.Max.x -= style.FramePadding.x;
16689
0
    if (node->HasCloseButton)
16690
0
    {
16691
0
        r.Max.x -= button_sz;
16692
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - style.FramePadding.x, r.Min.y);
16693
0
    }
16694
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
16695
0
    {
16696
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
16697
0
    }
16698
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
16699
0
    {
16700
0
        r.Max.x -= button_sz + style.FramePadding.x;
16701
0
        window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
16702
0
    }
16703
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
16704
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
16705
0
}
16706
16707
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
16708
0
{
16709
0
    ImGuiContext& g = *GImGui;
16710
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
16711
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16712
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
16713
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
16714
16715
    // Distribute size on given axis (with a desired size or equally)
16716
0
    const float w_avail = size_old[axis] - dock_spacing;
16717
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
16718
0
    {
16719
0
        size_new[axis] = size_new_desired[axis];
16720
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16721
0
    }
16722
0
    else
16723
0
    {
16724
0
        size_new[axis] = IM_FLOOR(w_avail * 0.5f);
16725
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16726
0
    }
16727
16728
    // Position each node
16729
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
16730
0
    {
16731
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
16732
0
    }
16733
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
16734
0
    {
16735
0
        pos_new[axis] = pos_old[axis];
16736
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
16737
0
    }
16738
0
}
16739
16740
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
16741
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
16742
0
{
16743
0
    ImGuiContext& g = *GImGui;
16744
16745
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
16746
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
16747
0
    float hs_w; // Half-size, longer axis
16748
0
    float hs_h; // Half-size, smaller axis
16749
0
    ImVec2 off; // Distance from edge or center
16750
0
    if (outer_docking)
16751
0
    {
16752
        //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
16753
        //hs_h = ImFloor(hs_w * 0.15f);
16754
        //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
16755
0
        hs_w = ImFloor(hs_for_central_nodes * 1.50f);
16756
0
        hs_h = ImFloor(hs_for_central_nodes * 0.80f);
16757
0
        off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h));
16758
0
    }
16759
0
    else
16760
0
    {
16761
0
        hs_w = ImFloor(hs_for_central_nodes);
16762
0
        hs_h = ImFloor(hs_for_central_nodes * 0.90f);
16763
0
        off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
16764
0
    }
16765
16766
0
    ImVec2 c = ImFloor(parent.GetCenter());
16767
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
16768
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
16769
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
16770
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
16771
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
16772
16773
0
    if (test_mouse_pos == NULL)
16774
0
        return false;
16775
16776
0
    ImRect hit_r = out_r;
16777
0
    if (!outer_docking)
16778
0
    {
16779
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
16780
0
        hit_r.Expand(ImFloor(hs_w * 0.30f));
16781
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
16782
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
16783
0
        float r_threshold_center = hs_w * 1.4f;
16784
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
16785
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
16786
0
            return (dir == ImGuiDir_None);
16787
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
16788
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
16789
0
    }
16790
0
    return hit_r.Contains(*test_mouse_pos);
16791
0
}
16792
16793
// host_node may be NULL if the window doesn't have a DockNode already.
16794
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
16795
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
16796
0
{
16797
0
    ImGuiContext& g = *GImGui;
16798
16799
    // There is an edge case when docking into a dockspace which only has inactive nodes.
16800
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
16801
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
16802
0
    if (payload_node == NULL)
16803
0
        payload_node = payload_window->DockNodeAsHost;
16804
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
16805
0
    if (ref_node_for_rect)
16806
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
16807
16808
    // Filter, figure out where we are allowed to dock
16809
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
16810
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
16811
0
    data->IsCenterAvailable = true;
16812
0
    if (is_outer_docking)
16813
0
        data->IsCenterAvailable = false;
16814
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking)
16815
0
        data->IsCenterAvailable = false;
16816
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
16817
0
        data->IsCenterAvailable = false;
16818
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
16819
0
        data->IsCenterAvailable = false;
16820
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
16821
0
        data->IsCenterAvailable = false;
16822
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
16823
0
        data->IsCenterAvailable = false;
16824
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
16825
0
        data->IsCenterAvailable = false;
16826
16827
0
    data->IsSidesAvailable = true;
16828
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit)
16829
0
        data->IsSidesAvailable = false;
16830
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
16831
0
        data->IsSidesAvailable = false;
16832
0
    else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther))
16833
0
        data->IsSidesAvailable = false;
16834
16835
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
16836
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
16837
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
16838
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
16839
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
16840
16841
    // Calculate drop shapes geometry for allowed splitting directions
16842
0
    IM_ASSERT(ImGuiDir_None == -1);
16843
0
    data->SplitNode = host_node;
16844
0
    data->SplitDir = ImGuiDir_None;
16845
0
    data->IsSplitDirExplicit = false;
16846
0
    if (!host_window->Collapsed)
16847
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16848
0
        {
16849
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
16850
0
                continue;
16851
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
16852
0
                continue;
16853
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
16854
0
            {
16855
0
                data->SplitDir = (ImGuiDir)dir;
16856
0
                data->IsSplitDirExplicit = true;
16857
0
            }
16858
0
        }
16859
16860
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
16861
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
16862
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
16863
0
        data->IsDropAllowed = false;
16864
16865
    // Calculate split area
16866
0
    data->SplitRatio = 0.0f;
16867
0
    if (data->SplitDir != ImGuiDir_None)
16868
0
    {
16869
0
        ImGuiDir split_dir = data->SplitDir;
16870
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16871
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
16872
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
16873
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
16874
16875
        // Calculate split ratio so we can pass it down the docking request
16876
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
16877
0
        data->FutureNode.Pos = pos_new;
16878
0
        data->FutureNode.Size = size_new;
16879
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
16880
0
    }
16881
0
}
16882
16883
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
16884
0
{
16885
0
    ImGuiContext& g = *GImGui;
16886
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
16887
16888
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
16889
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
16890
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
16891
16892
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
16893
0
    int overlay_draw_lists_count = 0;
16894
0
    ImDrawList* overlay_draw_lists[2];
16895
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
16896
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
16897
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
16898
16899
    // Draw main preview rectangle
16900
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
16901
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
16902
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
16903
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
16904
16905
    // Display area preview
16906
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
16907
0
    if (data->IsDropAllowed)
16908
0
    {
16909
0
        ImRect overlay_rect = data->FutureNode.Rect();
16910
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
16911
0
            overlay_rect.Min.y += GetFrameHeight();
16912
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
16913
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16914
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE));
16915
0
    }
16916
16917
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
16918
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
16919
0
    {
16920
        // Compute target tab bar geometry so we can locate our preview tabs
16921
0
        ImRect tab_bar_rect;
16922
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
16923
0
        ImVec2 tab_pos = tab_bar_rect.Min;
16924
0
        if (host_node && host_node->TabBar)
16925
0
        {
16926
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
16927
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
16928
0
            else
16929
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
16930
0
        }
16931
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
16932
0
        {
16933
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
16934
0
        }
16935
16936
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
16937
0
        if (root_payload->DockNodeAsHost)
16938
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
16939
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
16940
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
16941
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
16942
0
        {
16943
            // DockNode's TabBar may have non-window Tabs manually appended by user
16944
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
16945
0
            if (tab_bar_with_payload && payload_window == NULL)
16946
0
                continue;
16947
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
16948
0
                continue;
16949
16950
            // Calculate the tab bounding box for each payload window
16951
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
16952
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
16953
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
16954
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
16955
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
16956
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
16957
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16958
0
            {
16959
0
                ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
16960
0
                if (!tab_bar_rect.Contains(tab_bb))
16961
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
16962
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
16963
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
16964
0
                if (!tab_bar_rect.Contains(tab_bb))
16965
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
16966
0
            }
16967
0
            PopStyleColor();
16968
0
        }
16969
0
    }
16970
16971
    // Display drop boxes
16972
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
16973
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16974
0
    {
16975
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
16976
0
        {
16977
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
16978
0
            ImRect draw_r_in = draw_r;
16979
0
            draw_r_in.Expand(-2.0f);
16980
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
16981
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16982
0
            {
16983
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
16984
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
16985
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
16986
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
16987
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
16988
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
16989
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
16990
0
            }
16991
0
        }
16992
16993
        // Stop after ImGuiDir_None
16994
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
16995
0
            return;
16996
0
    }
16997
0
}
16998
16999
//-----------------------------------------------------------------------------
17000
// Docking: ImGuiDockNode Tree manipulation functions
17001
//-----------------------------------------------------------------------------
17002
// - DockNodeTreeSplit()
17003
// - DockNodeTreeMerge()
17004
// - DockNodeTreeUpdatePosSize()
17005
// - DockNodeTreeUpdateSplitterFindTouchingNode()
17006
// - DockNodeTreeUpdateSplitter()
17007
// - DockNodeTreeFindFallbackLeafNode()
17008
// - DockNodeTreeFindNodeByPos()
17009
//-----------------------------------------------------------------------------
17010
17011
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17012
0
{
17013
0
    ImGuiContext& g = *GImGui;
17014
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
17015
17016
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17017
0
    child_0->ParentNode = parent_node;
17018
17019
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17020
0
    child_1->ParentNode = parent_node;
17021
17022
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17023
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
17024
0
    parent_node->ChildNodes[0] = child_0;
17025
0
    parent_node->ChildNodes[1] = child_1;
17026
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17027
0
    parent_node->SplitAxis = split_axis;
17028
0
    parent_node->VisibleWindow = NULL;
17029
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17030
17031
0
    float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE);
17032
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
17033
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17034
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17035
0
    child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
17036
0
    child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
17037
17038
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
17039
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17040
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
17041
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
17042
17043
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17044
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17045
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17046
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17047
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17048
0
    child_0->UpdateMergedFlags();
17049
0
    child_1->UpdateMergedFlags();
17050
0
    parent_node->UpdateMergedFlags();
17051
0
    if (child_inheritor->IsCentralNode())
17052
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
17053
0
}
17054
17055
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
17056
0
{
17057
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
17058
0
    ImGuiContext& g = *GImGui;
17059
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
17060
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
17061
0
    IM_ASSERT(child_0 || child_1);
17062
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
17063
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
17064
0
    {
17065
0
        IM_ASSERT(parent_node->TabBar == NULL);
17066
0
        IM_ASSERT(parent_node->Windows.Size == 0);
17067
0
    }
17068
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
17069
17070
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
17071
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
17072
0
    if (child_0)
17073
0
    {
17074
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
17075
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
17076
0
    }
17077
0
    if (child_1)
17078
0
    {
17079
0
        DockNodeMoveWindows(parent_node, child_1);
17080
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
17081
0
    }
17082
0
    DockNodeApplyPosSizeToWindows(parent_node);
17083
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17084
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
17085
0
    parent_node->SizeRef = backup_last_explicit_size;
17086
17087
    // Flags transfer
17088
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
17089
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17090
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17091
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
17092
0
    parent_node->UpdateMergedFlags();
17093
17094
0
    if (child_0)
17095
0
    {
17096
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
17097
0
        IM_DELETE(child_0);
17098
0
    }
17099
0
    if (child_1)
17100
0
    {
17101
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
17102
0
        IM_DELETE(child_1);
17103
0
    }
17104
0
}
17105
17106
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
17107
// (Depth-first, Pre-Order)
17108
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
17109
0
{
17110
    // During the regular dock node update we write to all nodes.
17111
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
17112
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
17113
0
    if (write_to_node)
17114
0
    {
17115
0
        node->Pos = pos;
17116
0
        node->Size = size;
17117
0
    }
17118
17119
0
    if (node->IsLeafNode())
17120
0
        return;
17121
17122
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17123
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17124
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
17125
0
    ImVec2 child_0_size = size, child_1_size = size;
17126
17127
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
17128
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
17129
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
17130
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
17131
17132
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
17133
0
    {
17134
0
        ImGuiContext& g = *GImGui;
17135
0
        const float spacing = DOCKING_SPLITTER_SIZE;
17136
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17137
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
17138
17139
        // Size allocation policy
17140
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
17141
0
        const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
17142
17143
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
17144
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImFloor()
17145
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
17146
17147
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
17148
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
17149
0
        {
17150
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
17151
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17152
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17153
0
        }
17154
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
17155
0
        {
17156
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
17157
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
17158
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17159
0
        }
17160
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
17161
0
        {
17162
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
17163
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
17164
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
17165
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * split_ratio);
17166
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17167
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17168
0
        }
17169
17170
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
17171
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
17172
0
        {
17173
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
17174
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17175
0
        }
17176
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
17177
0
        {
17178
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
17179
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
17180
0
        }
17181
0
        else
17182
0
        {
17183
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
17184
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
17185
0
            child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5f));
17186
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17187
0
        }
17188
17189
0
        child_1_pos[axis] += spacing + child_0_size[axis];
17190
0
    }
17191
17192
0
    if (only_write_to_single_node == NULL)
17193
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
17194
17195
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
17196
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
17197
0
    if (child_0_recurse)
17198
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
17199
0
    if (child_1_recurse)
17200
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
17201
0
}
17202
17203
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
17204
0
{
17205
0
    if (node->IsLeafNode())
17206
0
    {
17207
0
        touching_nodes->push_back(node);
17208
0
        return;
17209
0
    }
17210
0
    if (node->ChildNodes[0]->IsVisible)
17211
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
17212
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
17213
0
    if (node->ChildNodes[1]->IsVisible)
17214
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
17215
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
17216
0
}
17217
17218
// (Depth-First, Pre-Order)
17219
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
17220
0
{
17221
0
    if (node->IsLeafNode())
17222
0
        return;
17223
17224
0
    ImGuiContext& g = *GImGui;
17225
17226
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17227
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17228
0
    if (child_0->IsVisible && child_1->IsVisible)
17229
0
    {
17230
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17231
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17232
0
        IM_ASSERT(axis != ImGuiAxis_None);
17233
0
        ImRect bb;
17234
0
        bb.Min = child_0->Pos;
17235
0
        bb.Max = child_1->Pos;
17236
0
        bb.Min[axis] += child_0->Size[axis];
17237
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17238
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17239
17240
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17241
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17242
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17243
0
        {
17244
0
            ImGuiWindow* window = g.CurrentWindow;
17245
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17246
0
        }
17247
0
        else
17248
0
        {
17249
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17250
            //bb.Max[axis] -= 1;
17251
0
            PushID(node->ID);
17252
17253
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17254
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17255
0
            float min_size = g.Style.WindowMinSize[axis];
17256
0
            float resize_limits[2];
17257
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17258
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17259
17260
0
            ImGuiID splitter_id = GetID("##Splitter");
17261
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17262
0
            {
17263
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17264
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17265
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17266
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17267
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17268
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17269
17270
                // [DEBUG] Render touching nodes & limits
17271
                /*
17272
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17273
                for (int n = 0; n < 2; n++)
17274
                {
17275
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17276
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17277
                    if (axis == ImGuiAxis_X)
17278
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17279
                    else
17280
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17281
                }
17282
                */
17283
0
            }
17284
17285
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17286
0
            float cur_size_0 = child_0->Size[axis];
17287
0
            float cur_size_1 = child_1->Size[axis];
17288
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17289
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17290
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17291
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17292
0
            {
17293
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17294
0
                {
17295
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17296
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17297
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17298
17299
                    // Lock the size of every node that is a sibling of the node we are touching
17300
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17301
0
                    for (int side_n = 0; side_n < 2; side_n++)
17302
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17303
0
                        {
17304
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17305
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17306
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17307
0
                            while (touching_node->ParentNode != node)
17308
0
                            {
17309
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17310
0
                                {
17311
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17312
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17313
0
                                    node_to_preserve->WantLockSizeOnce = true;
17314
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17315
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17316
0
                                }
17317
0
                                touching_node = touching_node->ParentNode;
17318
0
                            }
17319
0
                        }
17320
17321
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17322
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17323
0
                    MarkIniSettingsDirty();
17324
0
                }
17325
0
            }
17326
0
            PopID();
17327
0
        }
17328
0
    }
17329
17330
0
    if (child_0->IsVisible)
17331
0
        DockNodeTreeUpdateSplitter(child_0);
17332
0
    if (child_1->IsVisible)
17333
0
        DockNodeTreeUpdateSplitter(child_1);
17334
0
}
17335
17336
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17337
0
{
17338
0
    if (node->IsLeafNode())
17339
0
        return node;
17340
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17341
0
        return leaf_node;
17342
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17343
0
        return leaf_node;
17344
0
    return NULL;
17345
0
}
17346
17347
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17348
0
{
17349
0
    if (!node->IsVisible)
17350
0
        return NULL;
17351
17352
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17353
0
    ImRect r(node->Pos, node->Pos + node->Size);
17354
0
    r.Expand(dock_spacing * 0.5f);
17355
0
    bool inside = r.Contains(pos);
17356
0
    if (!inside)
17357
0
        return NULL;
17358
17359
0
    if (node->IsLeafNode())
17360
0
        return node;
17361
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17362
0
        return hovered_node;
17363
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17364
0
        return hovered_node;
17365
17366
    // This means we are hovering over the splitter/spacing of a parent node
17367
0
    return node;
17368
0
}
17369
17370
//-----------------------------------------------------------------------------
17371
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17372
//-----------------------------------------------------------------------------
17373
// - SetWindowDock() [Internal]
17374
// - DockSpace()
17375
// - DockSpaceOverViewport()
17376
//-----------------------------------------------------------------------------
17377
17378
// [Internal] Called via SetNextWindowDockID()
17379
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17380
0
{
17381
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17382
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17383
0
        return;
17384
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17385
17386
0
    if (window->DockId == dock_id)
17387
0
        return;
17388
17389
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17390
0
    ImGuiContext* ctx = GImGui;
17391
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17392
0
        if (new_node->IsSplitNode())
17393
0
        {
17394
            // Policy: Find central node or latest focused node. We first move back to our root node.
17395
0
            new_node = DockNodeGetRootNode(new_node);
17396
0
            if (new_node->CentralNode)
17397
0
            {
17398
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
17399
0
                dock_id = new_node->CentralNode->ID;
17400
0
            }
17401
0
            else
17402
0
            {
17403
0
                dock_id = new_node->LastFocusedNodeId;
17404
0
            }
17405
0
        }
17406
17407
0
    if (window->DockId == dock_id)
17408
0
        return;
17409
17410
0
    if (window->DockNode)
17411
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
17412
0
    window->DockId = dock_id;
17413
0
}
17414
17415
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
17416
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
17417
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
17418
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
17419
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
17420
0
{
17421
0
    ImGuiContext* ctx = GImGui;
17422
0
    ImGuiContext& g = *ctx;
17423
0
    ImGuiWindow* window = GetCurrentWindowRead();
17424
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17425
0
        return 0;
17426
17427
    // Early out if parent window is hidden/collapsed
17428
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
17429
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
17430
0
    if (window->SkipItems)
17431
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
17432
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
17433
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
17434
17435
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
17436
0
    IM_ASSERT(id != 0);
17437
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
17438
0
    if (!node)
17439
0
    {
17440
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
17441
0
        node = DockContextAddNode(ctx, id);
17442
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
17443
0
    }
17444
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
17445
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
17446
0
    node->SharedFlags = flags;
17447
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
17448
17449
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
17450
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
17451
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
17452
0
    {
17453
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
17454
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17455
0
        return id;
17456
0
    }
17457
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17458
17459
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
17460
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
17461
0
    {
17462
0
        node->LastFrameAlive = g.FrameCount;
17463
0
        return id;
17464
0
    }
17465
17466
0
    const ImVec2 content_avail = GetContentRegionAvail();
17467
0
    ImVec2 size = ImFloor(size_arg);
17468
0
    if (size.x <= 0.0f)
17469
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
17470
0
    if (size.y <= 0.0f)
17471
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
17472
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17473
17474
0
    node->Pos = window->DC.CursorPos;
17475
0
    node->Size = node->SizeRef = size;
17476
0
    SetNextWindowPos(node->Pos);
17477
0
    SetNextWindowSize(node->Size);
17478
0
    g.NextWindowData.PosUndock = false;
17479
17480
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
17481
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
17482
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
17483
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
17484
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
17485
0
    window_flags |= ImGuiWindowFlags_NoBackground;
17486
17487
0
    char title[256];
17488
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
17489
17490
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
17491
0
    Begin(title, NULL, window_flags);
17492
0
    PopStyleVar();
17493
17494
0
    ImGuiWindow* host_window = g.CurrentWindow;
17495
0
    DockNodeSetupHostWindow(node, host_window);
17496
0
    host_window->ChildId = window->GetID(title);
17497
0
    node->OnlyNodeWithWindows = NULL;
17498
17499
0
    IM_ASSERT(node->IsRootNode());
17500
17501
    // We need to handle the rare case were a central node is missing.
17502
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
17503
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
17504
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
17505
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
17506
    // as it doesn't make sense for an empty dockspace to not have this property.
17507
0
    if (node->IsLeafNode() && !node->IsCentralNode())
17508
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17509
17510
    // Update the node
17511
0
    DockNodeUpdate(node);
17512
17513
0
    End();
17514
17515
0
    ImRect bb(node->Pos, node->Pos + size);
17516
0
    ItemSize(size);
17517
0
    ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
17518
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
17519
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
17520
17521
0
    return id;
17522
0
}
17523
17524
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
17525
// The limitation with this call is that your window won't have a menu bar.
17526
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
17527
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
17528
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
17529
0
{
17530
0
    if (viewport == NULL)
17531
0
        viewport = GetMainViewport();
17532
17533
0
    SetNextWindowPos(viewport->WorkPos);
17534
0
    SetNextWindowSize(viewport->WorkSize);
17535
0
    SetNextWindowViewport(viewport->ID);
17536
17537
0
    ImGuiWindowFlags host_window_flags = 0;
17538
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
17539
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
17540
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
17541
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
17542
17543
0
    char label[32];
17544
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
17545
17546
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
17547
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
17548
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
17549
0
    Begin(label, NULL, host_window_flags);
17550
0
    PopStyleVar(3);
17551
17552
0
    ImGuiID dockspace_id = GetID("DockSpace");
17553
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
17554
0
    End();
17555
17556
0
    return dockspace_id;
17557
0
}
17558
17559
//-----------------------------------------------------------------------------
17560
// Docking: Builder Functions
17561
//-----------------------------------------------------------------------------
17562
// Very early end-user API to manipulate dock nodes.
17563
// Only available in imgui_internal.h. Expect this API to change/break!
17564
// It is expected that those functions are all called _before_ the dockspace node submission.
17565
//-----------------------------------------------------------------------------
17566
// - DockBuilderDockWindow()
17567
// - DockBuilderGetNode()
17568
// - DockBuilderSetNodePos()
17569
// - DockBuilderSetNodeSize()
17570
// - DockBuilderAddNode()
17571
// - DockBuilderRemoveNode()
17572
// - DockBuilderRemoveNodeChildNodes()
17573
// - DockBuilderRemoveNodeDockedWindows()
17574
// - DockBuilderSplitNode()
17575
// - DockBuilderCopyNodeRec()
17576
// - DockBuilderCopyNode()
17577
// - DockBuilderCopyWindowSettings()
17578
// - DockBuilderCopyDockSpace()
17579
// - DockBuilderFinish()
17580
//-----------------------------------------------------------------------------
17581
17582
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
17583
0
{
17584
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
17585
0
    ImGuiID window_id = ImHashStr(window_name);
17586
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
17587
0
    {
17588
        // Apply to created window
17589
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
17590
0
        window->DockOrder = -1;
17591
0
    }
17592
0
    else
17593
0
    {
17594
        // Apply to settings
17595
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
17596
0
        if (settings == NULL)
17597
0
            settings = CreateNewWindowSettings(window_name);
17598
0
        settings->DockId = node_id;
17599
0
        settings->DockOrder = -1;
17600
0
    }
17601
0
}
17602
17603
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
17604
0
{
17605
0
    ImGuiContext* ctx = GImGui;
17606
0
    return DockContextFindNodeByID(ctx, node_id);
17607
0
}
17608
17609
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
17610
0
{
17611
0
    ImGuiContext* ctx = GImGui;
17612
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17613
0
    if (node == NULL)
17614
0
        return;
17615
0
    node->Pos = pos;
17616
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
17617
0
}
17618
17619
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
17620
0
{
17621
0
    ImGuiContext* ctx = GImGui;
17622
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17623
0
    if (node == NULL)
17624
0
        return;
17625
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17626
0
    node->Size = node->SizeRef = size;
17627
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17628
0
}
17629
17630
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
17631
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
17632
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
17633
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
17634
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
17635
// - Use (id == 0) to let the system allocate a node identifier.
17636
// - Existing node with a same id will be removed.
17637
ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags)
17638
0
{
17639
0
    ImGuiContext* ctx = GImGui;
17640
17641
0
    if (id != 0)
17642
0
        DockBuilderRemoveNode(id);
17643
17644
0
    ImGuiDockNode* node = NULL;
17645
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
17646
0
    {
17647
0
        DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
17648
0
        node = DockContextFindNodeByID(ctx, id);
17649
0
    }
17650
0
    else
17651
0
    {
17652
0
        node = DockContextAddNode(ctx, id);
17653
0
        node->SetLocalFlags(flags);
17654
0
    }
17655
0
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
17656
0
    return node->ID;
17657
0
}
17658
17659
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
17660
0
{
17661
0
    ImGuiContext* ctx = GImGui;
17662
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17663
0
    if (node == NULL)
17664
0
        return;
17665
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
17666
0
    DockBuilderRemoveNodeChildNodes(node_id);
17667
    // Node may have moved or deleted if e.g. any merge happened
17668
0
    node = DockContextFindNodeByID(ctx, node_id);
17669
0
    if (node == NULL)
17670
0
        return;
17671
0
    if (node->IsCentralNode() && node->ParentNode)
17672
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17673
0
    DockContextRemoveNode(ctx, node, true);
17674
0
}
17675
17676
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
17677
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
17678
0
{
17679
0
    ImGuiContext* ctx = GImGui;
17680
0
    ImGuiDockContext* dc  = &ctx->DockContext;
17681
17682
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
17683
0
    if (root_id && root_node == NULL)
17684
0
        return;
17685
0
    bool has_central_node = false;
17686
17687
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
17688
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
17689
17690
    // Process active windows
17691
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
17692
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
17693
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17694
0
        {
17695
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
17696
0
            if (want_removal)
17697
0
            {
17698
0
                if (node->IsCentralNode())
17699
0
                    has_central_node = true;
17700
0
                if (root_id != 0)
17701
0
                    DockContextQueueNotifyRemovedNode(ctx, node);
17702
0
                if (root_node)
17703
0
                {
17704
0
                    DockNodeMoveWindows(root_node, node);
17705
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
17706
0
                }
17707
0
                nodes_to_remove.push_back(node);
17708
0
            }
17709
0
        }
17710
17711
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
17712
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
17713
0
    if (root_node)
17714
0
    {
17715
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
17716
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
17717
0
    }
17718
17719
    // Apply to settings
17720
0
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
17721
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
17722
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
17723
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
17724
0
                {
17725
0
                    settings->DockId = root_id;
17726
0
                    break;
17727
0
                }
17728
17729
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
17730
0
    if (nodes_to_remove.Size > 1)
17731
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
17732
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
17733
0
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
17734
17735
0
    if (root_id == 0)
17736
0
    {
17737
0
        dc->Nodes.Clear();
17738
0
        dc->Requests.clear();
17739
0
    }
17740
0
    else if (has_central_node)
17741
0
    {
17742
0
        root_node->CentralNode = root_node;
17743
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17744
0
    }
17745
0
}
17746
17747
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
17748
0
{
17749
    // Clear references in settings
17750
0
    ImGuiContext* ctx = GImGui;
17751
0
    ImGuiContext& g = *ctx;
17752
0
    if (clear_settings_refs)
17753
0
    {
17754
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17755
0
        {
17756
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
17757
0
            if (!want_removal && settings->DockId != 0)
17758
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
17759
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
17760
0
                        want_removal = true;
17761
0
            if (want_removal)
17762
0
                settings->DockId = 0;
17763
0
        }
17764
0
    }
17765
17766
    // Clear references in windows
17767
0
    for (int n = 0; n < g.Windows.Size; n++)
17768
0
    {
17769
0
        ImGuiWindow* window = g.Windows[n];
17770
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
17771
0
        if (want_removal)
17772
0
        {
17773
0
            const ImGuiID backup_dock_id = window->DockId;
17774
0
            IM_UNUSED(backup_dock_id);
17775
0
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
17776
0
            if (!clear_settings_refs)
17777
0
                IM_ASSERT(window->DockId == backup_dock_id);
17778
0
        }
17779
0
    }
17780
0
}
17781
17782
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
17783
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
17784
// FIXME-DOCK: We are not exposing nor using split_outer.
17785
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
17786
0
{
17787
0
    ImGuiContext& g = *GImGui;
17788
0
    IM_ASSERT(split_dir != ImGuiDir_None);
17789
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
17790
17791
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
17792
0
    if (node == NULL)
17793
0
    {
17794
0
        IM_ASSERT(node != NULL);
17795
0
        return 0;
17796
0
    }
17797
17798
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
17799
17800
0
    ImGuiDockRequest req;
17801
0
    req.Type = ImGuiDockRequestType_Split;
17802
0
    req.DockTargetWindow = NULL;
17803
0
    req.DockTargetNode = node;
17804
0
    req.DockPayload = NULL;
17805
0
    req.DockSplitDir = split_dir;
17806
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
17807
0
    req.DockSplitOuter = false;
17808
0
    DockContextProcessDock(&g, &req);
17809
17810
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
17811
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
17812
0
    if (out_id_at_dir)
17813
0
        *out_id_at_dir = id_at_dir;
17814
0
    if (out_id_at_opposite_dir)
17815
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
17816
0
    return id_at_dir;
17817
0
}
17818
17819
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
17820
0
{
17821
0
    ImGuiContext& g = *GImGui;
17822
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
17823
0
    dst_node->SharedFlags = src_node->SharedFlags;
17824
0
    dst_node->LocalFlags = src_node->LocalFlags;
17825
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17826
0
    dst_node->Pos = src_node->Pos;
17827
0
    dst_node->Size = src_node->Size;
17828
0
    dst_node->SizeRef = src_node->SizeRef;
17829
0
    dst_node->SplitAxis = src_node->SplitAxis;
17830
0
    dst_node->UpdateMergedFlags();
17831
17832
0
    out_node_remap_pairs->push_back(src_node->ID);
17833
0
    out_node_remap_pairs->push_back(dst_node->ID);
17834
17835
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
17836
0
        if (src_node->ChildNodes[child_n])
17837
0
        {
17838
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
17839
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
17840
0
        }
17841
17842
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
17843
0
    return dst_node;
17844
0
}
17845
17846
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
17847
0
{
17848
0
    ImGuiContext* ctx = GImGui;
17849
0
    IM_ASSERT(src_node_id != 0);
17850
0
    IM_ASSERT(dst_node_id != 0);
17851
0
    IM_ASSERT(out_node_remap_pairs != NULL);
17852
17853
0
    DockBuilderRemoveNode(dst_node_id);
17854
17855
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
17856
0
    IM_ASSERT(src_node != NULL);
17857
17858
0
    out_node_remap_pairs->clear();
17859
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
17860
17861
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
17862
0
}
17863
17864
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
17865
0
{
17866
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
17867
0
    if (src_window == NULL)
17868
0
        return;
17869
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
17870
0
    {
17871
0
        dst_window->Pos = src_window->Pos;
17872
0
        dst_window->Size = src_window->Size;
17873
0
        dst_window->SizeFull = src_window->SizeFull;
17874
0
        dst_window->Collapsed = src_window->Collapsed;
17875
0
    }
17876
0
    else
17877
0
    {
17878
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
17879
0
        if (!dst_settings)
17880
0
            dst_settings = CreateNewWindowSettings(dst_name);
17881
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
17882
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
17883
0
        {
17884
0
            dst_settings->ViewportPos = window_pos_2ih;
17885
0
            dst_settings->ViewportId = src_window->ViewportId;
17886
0
            dst_settings->Pos = ImVec2ih(0, 0);
17887
0
        }
17888
0
        else
17889
0
        {
17890
0
            dst_settings->Pos = window_pos_2ih;
17891
0
        }
17892
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
17893
0
        dst_settings->Collapsed = src_window->Collapsed;
17894
0
    }
17895
0
}
17896
17897
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
17898
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
17899
0
{
17900
0
    ImGuiContext& g = *GImGui;
17901
0
    IM_ASSERT(src_dockspace_id != 0);
17902
0
    IM_ASSERT(dst_dockspace_id != 0);
17903
0
    IM_ASSERT(in_window_remap_pairs != NULL);
17904
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
17905
17906
    // Duplicate entire dock
17907
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
17908
    // whereas we could attempt to at least keep them together in a new, same floating node.
17909
0
    ImVector<ImGuiID> node_remap_pairs;
17910
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
17911
17912
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
17913
    // (The windows associated to src_dockspace_id are staying in place)
17914
0
    ImVector<ImGuiID> src_windows;
17915
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
17916
0
    {
17917
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
17918
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
17919
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
17920
0
        src_windows.push_back(src_window_id);
17921
17922
        // Search in the remapping tables
17923
0
        ImGuiID src_dock_id = 0;
17924
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
17925
0
            src_dock_id = src_window->DockId;
17926
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
17927
0
            src_dock_id = src_window_settings->DockId;
17928
0
        ImGuiID dst_dock_id = 0;
17929
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
17930
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
17931
0
            {
17932
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
17933
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
17934
0
                break;
17935
0
            }
17936
17937
0
        if (dst_dock_id != 0)
17938
0
        {
17939
            // Docked windows gets redocked into the new node hierarchy.
17940
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
17941
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
17942
0
        }
17943
0
        else
17944
0
        {
17945
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
17946
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
17947
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
17948
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
17949
0
        }
17950
0
    }
17951
17952
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
17953
    // Find those windows and move to them to the cloned dock node. This may be optional?
17954
    // Dock those are a second step as undocking would invalidate source dock nodes.
17955
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
17956
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
17957
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
17958
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
17959
0
        {
17960
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
17961
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
17962
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17963
0
            {
17964
0
                ImGuiWindow* window = node->Windows[window_n];
17965
0
                if (src_windows.contains(window->ID))
17966
0
                    continue;
17967
17968
                // Docked windows gets redocked into the new node hierarchy.
17969
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
17970
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
17971
0
            }
17972
0
        }
17973
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
17974
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
17975
0
}
17976
17977
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
17978
void ImGui::DockBuilderFinish(ImGuiID root_id)
17979
0
{
17980
0
    ImGuiContext* ctx = GImGui;
17981
    //DockContextRebuild(ctx);
17982
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
17983
0
}
17984
17985
//-----------------------------------------------------------------------------
17986
// Docking: Begin/End Support Functions (called from Begin/End)
17987
//-----------------------------------------------------------------------------
17988
// - GetWindowAlwaysWantOwnTabBar()
17989
// - DockContextBindNodeToWindow()
17990
// - BeginDocked()
17991
// - BeginDockableDragDropSource()
17992
// - BeginDockableDragDropTarget()
17993
//-----------------------------------------------------------------------------
17994
17995
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
17996
46.9k
{
17997
46.9k
    ImGuiContext& g = *GImGui;
17998
46.9k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
17999
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18000
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18001
0
                return true;
18002
46.9k
    return false;
18003
46.9k
}
18004
18005
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18006
0
{
18007
0
    ImGuiContext& g = *ctx;
18008
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18009
0
    IM_ASSERT(window->DockNode == NULL);
18010
18011
    // We should not be docking into a split node (SetWindowDock should avoid this)
18012
0
    if (node && node->IsSplitNode())
18013
0
    {
18014
0
        DockContextProcessUndockWindow(ctx, window);
18015
0
        return NULL;
18016
0
    }
18017
18018
    // Create node
18019
0
    if (node == NULL)
18020
0
    {
18021
0
        node = DockContextAddNode(ctx, window->DockId);
18022
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18023
0
        node->LastFrameAlive = g.FrameCount;
18024
0
    }
18025
18026
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18027
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18028
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
18029
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18030
0
    if (!node->IsVisible)
18031
0
    {
18032
0
        ImGuiDockNode* ancestor_node = node;
18033
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18034
0
            ancestor_node = ancestor_node->ParentNode;
18035
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18036
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
18037
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
18038
0
    }
18039
18040
    // Add window to node
18041
0
    bool node_was_visible = node->IsVisible;
18042
0
    DockNodeAddWindow(node, window, true);
18043
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
18044
0
    IM_ASSERT(node == window->DockNode);
18045
0
    return node;
18046
0
}
18047
18048
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
18049
0
{
18050
0
    ImGuiContext* ctx = GImGui;
18051
0
    ImGuiContext& g = *ctx;
18052
18053
    // Clear fields ahead so most early-out paths don't have to do it
18054
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
18055
18056
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
18057
0
    if (auto_dock_node)
18058
0
    {
18059
0
        if (window->DockId == 0)
18060
0
        {
18061
0
            IM_ASSERT(window->DockNode == NULL);
18062
0
            window->DockId = DockContextGenNodeID(ctx);
18063
0
        }
18064
0
    }
18065
0
    else
18066
0
    {
18067
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
18068
0
        bool want_undock = false;
18069
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
18070
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
18071
0
        if (want_undock)
18072
0
        {
18073
0
            DockContextProcessUndockWindow(ctx, window);
18074
0
            return;
18075
0
        }
18076
0
    }
18077
18078
    // Bind to our dock node
18079
0
    ImGuiDockNode* node = window->DockNode;
18080
0
    if (node != NULL)
18081
0
        IM_ASSERT(window->DockId == node->ID);
18082
0
    if (window->DockId != 0 && node == NULL)
18083
0
    {
18084
0
        node = DockContextBindNodeToWindow(ctx, window);
18085
0
        if (node == NULL)
18086
0
            return;
18087
0
    }
18088
18089
#if 0
18090
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
18091
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
18092
    {
18093
        DockContextProcessUndockWindow(ctx, window);
18094
        return;
18095
    }
18096
#endif
18097
18098
    // Undock if our dockspace node disappeared
18099
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
18100
0
    if (node->LastFrameAlive < g.FrameCount)
18101
0
    {
18102
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
18103
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18104
0
        if (root_node->LastFrameAlive < g.FrameCount)
18105
0
            DockContextProcessUndockWindow(ctx, window);
18106
0
        else
18107
0
            window->DockIsActive = true;
18108
0
        return;
18109
0
    }
18110
18111
    // Store style overrides
18112
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18113
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18114
18115
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
18116
    // and never create neither a host window neither a tab bar.
18117
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
18118
0
    if (node->HostWindow == NULL)
18119
0
    {
18120
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
18121
0
            window->DockIsActive = true;
18122
0
        if (node->Windows.Size > 1)
18123
0
            DockNodeHideWindowDuringHostWindowCreation(window);
18124
0
        return;
18125
0
    }
18126
18127
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
18128
0
    IM_ASSERT(node->HostWindow);
18129
0
    IM_ASSERT(node->IsLeafNode());
18130
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
18131
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
18132
18133
    // Undock if we are submitted earlier than the host window
18134
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
18135
0
    {
18136
0
        DockContextProcessUndockWindow(ctx, window);
18137
0
        return;
18138
0
    }
18139
18140
    // Position/Size window
18141
0
    SetNextWindowPos(node->Pos);
18142
0
    SetNextWindowSize(node->Size);
18143
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
18144
0
    window->DockIsActive = true;
18145
0
    window->DockNodeIsVisible = true;
18146
0
    window->DockTabIsVisible = false;
18147
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18148
0
        return;
18149
18150
    // When the window is selected we mark it as visible.
18151
0
    if (node->VisibleWindow == window)
18152
0
        window->DockTabIsVisible = true;
18153
18154
    // Update window flag
18155
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
18156
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
18157
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
18158
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
18159
0
    else
18160
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
18161
18162
    // Save new dock order only if the window has been visible once already
18163
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
18164
0
    if (node->TabBar && window->WasActive)
18165
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
18166
18167
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
18168
0
        *p_open = false;
18169
18170
    // Update ChildId to allow returning from Child to Parent with Escape
18171
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
18172
0
    window->ChildId = parent_window->GetID(window->Name);
18173
0
}
18174
18175
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
18176
2
{
18177
2
    ImGuiContext& g = *GImGui;
18178
2
    IM_ASSERT(g.ActiveId == window->MoveId);
18179
2
    IM_ASSERT(g.MovingWindow == window);
18180
2
    IM_ASSERT(g.CurrentWindow == window);
18181
18182
2
    g.LastItemData.ID = window->MoveId;
18183
2
    window = window->RootWindowDockTree;
18184
2
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18185
2
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
18186
2
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
18187
0
    {
18188
0
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
18189
0
        EndDragDropSource();
18190
18191
        // Store style overrides
18192
0
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18193
0
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18194
0
    }
18195
2
}
18196
18197
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
18198
0
{
18199
0
    ImGuiContext* ctx = GImGui;
18200
0
    ImGuiContext& g = *ctx;
18201
18202
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
18203
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18204
0
    if (!g.DragDropActive)
18205
0
        return;
18206
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
18207
0
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
18208
0
        return;
18209
18210
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
18211
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
18212
0
    const ImGuiPayload* payload = &g.DragDropPayload;
18213
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
18214
0
    {
18215
0
        EndDragDropTarget();
18216
0
        return;
18217
0
    }
18218
18219
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
18220
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
18221
0
    {
18222
        // Select target node
18223
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
18224
0
        bool dock_into_floating_window = false;
18225
0
        ImGuiDockNode* node = NULL;
18226
0
        if (window->DockNodeAsHost)
18227
0
        {
18228
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
18229
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18230
18231
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18232
            // In this case we need to fallback into any leaf mode, possibly the central node.
18233
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18234
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18235
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18236
0
        }
18237
0
        else
18238
0
        {
18239
0
            if (window->DockNode)
18240
0
                node = window->DockNode;
18241
0
            else
18242
0
                dock_into_floating_window = true; // Dock into a regular window
18243
0
        }
18244
18245
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18246
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18247
18248
        // Preview docking request and find out split direction/ratio
18249
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18250
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18251
0
        if (do_preview && (node != NULL || dock_into_floating_window))
18252
0
        {
18253
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18254
0
            ImGuiDockPreviewData split_inner;
18255
0
            ImGuiDockPreviewData split_outer;
18256
0
            ImGuiDockPreviewData* split_data = &split_inner;
18257
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18258
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18259
0
                {
18260
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18261
0
                    if (split_outer.IsSplitDirExplicit)
18262
0
                        split_data = &split_outer;
18263
0
                }
18264
0
            if (!node || node->IsLeafNode())
18265
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18266
0
            if (split_data == &split_outer)
18267
0
                split_inner.IsDropAllowed = false;
18268
18269
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18270
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18271
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18272
18273
            // Queue docking request
18274
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18275
0
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18276
0
        }
18277
0
    }
18278
0
    EndDragDropTarget();
18279
0
}
18280
18281
//-----------------------------------------------------------------------------
18282
// Docking: Settings
18283
//-----------------------------------------------------------------------------
18284
// - DockSettingsRenameNodeReferences()
18285
// - DockSettingsRemoveNodeReferences()
18286
// - DockSettingsFindNodeSettings()
18287
// - DockSettingsHandler_ApplyAll()
18288
// - DockSettingsHandler_ReadOpen()
18289
// - DockSettingsHandler_ReadLine()
18290
// - DockSettingsHandler_DockNodeToSettings()
18291
// - DockSettingsHandler_WriteAll()
18292
//-----------------------------------------------------------------------------
18293
18294
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18295
0
{
18296
0
    ImGuiContext& g = *GImGui;
18297
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18298
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18299
0
    {
18300
0
        ImGuiWindow* window = g.Windows[window_n];
18301
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18302
0
            window->DockId = new_node_id;
18303
0
    }
18304
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18305
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18306
0
        if (settings->DockId == old_node_id)
18307
0
            settings->DockId = new_node_id;
18308
0
}
18309
18310
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18311
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18312
0
{
18313
0
    ImGuiContext& g = *GImGui;
18314
0
    int found = 0;
18315
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18316
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18317
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18318
0
            if (settings->DockId == node_ids[node_n])
18319
0
            {
18320
0
                settings->DockId = 0;
18321
0
                settings->DockOrder = -1;
18322
0
                if (++found < node_ids_count)
18323
0
                    break;
18324
0
                return;
18325
0
            }
18326
0
}
18327
18328
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18329
0
{
18330
    // FIXME-OPT
18331
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18332
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18333
0
        if (dc->NodesSettings[n].ID == id)
18334
0
            return &dc->NodesSettings[n];
18335
0
    return NULL;
18336
0
}
18337
18338
// Clear settings data
18339
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18340
0
{
18341
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18342
0
    dc->NodesSettings.clear();
18343
0
    DockContextClearNodes(ctx, 0, true);
18344
0
}
18345
18346
// Recreate nodes based on settings data
18347
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18348
0
{
18349
    // Prune settings at boot time only
18350
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18351
0
    if (ctx->Windows.Size == 0)
18352
0
        DockContextPruneUnusedSettingsNodes(ctx);
18353
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18354
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18355
0
}
18356
18357
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18358
0
{
18359
0
    if (strcmp(name, "Data") != 0)
18360
0
        return NULL;
18361
0
    return (void*)1;
18362
0
}
18363
18364
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18365
0
{
18366
0
    char c = 0;
18367
0
    int x = 0, y = 0;
18368
0
    int r = 0;
18369
18370
    // Parsing, e.g.
18371
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18372
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18373
    // Important: this code expect currently fields in a fixed order.
18374
0
    ImGuiDockNodeSettings node;
18375
0
    line = ImStrSkipBlank(line);
18376
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18377
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18378
0
    else return;
18379
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
18380
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
18381
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
18382
0
    if (node.ParentNodeId == 0)
18383
0
    {
18384
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
18385
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
18386
0
    }
18387
0
    else
18388
0
    {
18389
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
18390
0
    }
18391
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
18392
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
18393
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
18394
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
18395
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
18396
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
18397
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
18398
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
18399
0
    if (node.ParentNodeId != 0)
18400
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
18401
0
            node.Depth = parent_settings->Depth + 1;
18402
0
    ctx->DockContext.NodesSettings.push_back(node);
18403
0
}
18404
18405
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
18406
0
{
18407
0
    ImGuiDockNodeSettings node_settings;
18408
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
18409
0
    node_settings.ID = node->ID;
18410
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
18411
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
18412
0
    node_settings.SelectedTabId = node->SelectedTabId;
18413
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
18414
0
    node_settings.Depth = (char)depth;
18415
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
18416
0
    node_settings.Pos = ImVec2ih(node->Pos);
18417
0
    node_settings.Size = ImVec2ih(node->Size);
18418
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
18419
0
    dc->NodesSettings.push_back(node_settings);
18420
0
    if (node->ChildNodes[0])
18421
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
18422
0
    if (node->ChildNodes[1])
18423
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
18424
0
}
18425
18426
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
18427
0
{
18428
0
    ImGuiContext& g = *ctx;
18429
0
    ImGuiDockContext* dc = &ctx->DockContext;
18430
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18431
0
        return;
18432
18433
    // Gather settings data
18434
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
18435
0
    dc->NodesSettings.resize(0);
18436
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
18437
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18438
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18439
0
            if (node->IsRootNode())
18440
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
18441
18442
0
    int max_depth = 0;
18443
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18444
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
18445
18446
    // Write to text buffer
18447
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
18448
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18449
0
    {
18450
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
18451
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
18452
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
18453
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
18454
0
        if (node_settings->ParentNodeId)
18455
0
        {
18456
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
18457
0
        }
18458
0
        else
18459
0
        {
18460
0
            if (node_settings->ParentWindowId)
18461
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
18462
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
18463
0
        }
18464
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
18465
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
18466
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
18467
0
            buf->appendf(" NoResize=1");
18468
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
18469
0
            buf->appendf(" CentralNode=1");
18470
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
18471
0
            buf->appendf(" NoTabBar=1");
18472
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
18473
0
            buf->appendf(" HiddenTabBar=1");
18474
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
18475
0
            buf->appendf(" NoWindowMenuButton=1");
18476
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
18477
0
            buf->appendf(" NoCloseButton=1");
18478
0
        if (node_settings->SelectedTabId)
18479
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
18480
18481
#if IMGUI_DEBUG_INI_SETTINGS
18482
        // [DEBUG] Include comments in the .ini file to ease debugging
18483
        if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
18484
        {
18485
            buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
18486
            if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
18487
                buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
18488
            // Iterate settings so we can give info about windows that didn't exist during the session.
18489
            int contains_window = 0;
18490
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18491
                if (settings->DockId == node_settings->ID)
18492
                {
18493
                    if (contains_window++ == 0)
18494
                        buf->appendf(" ; contains ");
18495
                    buf->appendf("'%s' ", settings->GetName());
18496
                }
18497
        }
18498
#endif
18499
0
        buf->appendf("\n");
18500
0
    }
18501
0
    buf->appendf("\n");
18502
0
}
18503
18504
18505
//-----------------------------------------------------------------------------
18506
// [SECTION] PLATFORM DEPENDENT HELPERS
18507
//-----------------------------------------------------------------------------
18508
18509
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
18510
18511
#ifdef _MSC_VER
18512
#pragma comment(lib, "user32")
18513
#pragma comment(lib, "kernel32")
18514
#endif
18515
18516
// Win32 clipboard implementation
18517
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
18518
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18519
{
18520
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18521
    g.ClipboardHandlerData.clear();
18522
    if (!::OpenClipboard(NULL))
18523
        return NULL;
18524
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
18525
    if (wbuf_handle == NULL)
18526
    {
18527
        ::CloseClipboard();
18528
        return NULL;
18529
    }
18530
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
18531
    {
18532
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
18533
        g.ClipboardHandlerData.resize(buf_len);
18534
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
18535
    }
18536
    ::GlobalUnlock(wbuf_handle);
18537
    ::CloseClipboard();
18538
    return g.ClipboardHandlerData.Data;
18539
}
18540
18541
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18542
{
18543
    if (!::OpenClipboard(NULL))
18544
        return;
18545
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
18546
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
18547
    if (wbuf_handle == NULL)
18548
    {
18549
        ::CloseClipboard();
18550
        return;
18551
    }
18552
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
18553
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
18554
    ::GlobalUnlock(wbuf_handle);
18555
    ::EmptyClipboard();
18556
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
18557
        ::GlobalFree(wbuf_handle);
18558
    ::CloseClipboard();
18559
}
18560
18561
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
18562
18563
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
18564
static PasteboardRef main_clipboard = 0;
18565
18566
// OSX clipboard implementation
18567
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
18568
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18569
{
18570
    if (!main_clipboard)
18571
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18572
    PasteboardClear(main_clipboard);
18573
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
18574
    if (cf_data)
18575
    {
18576
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
18577
        CFRelease(cf_data);
18578
    }
18579
}
18580
18581
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18582
{
18583
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18584
    if (!main_clipboard)
18585
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18586
    PasteboardSynchronize(main_clipboard);
18587
18588
    ItemCount item_count = 0;
18589
    PasteboardGetItemCount(main_clipboard, &item_count);
18590
    for (ItemCount i = 0; i < item_count; i++)
18591
    {
18592
        PasteboardItemID item_id = 0;
18593
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
18594
        CFArrayRef flavor_type_array = 0;
18595
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
18596
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
18597
        {
18598
            CFDataRef cf_data;
18599
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
18600
            {
18601
                g.ClipboardHandlerData.clear();
18602
                int length = (int)CFDataGetLength(cf_data);
18603
                g.ClipboardHandlerData.resize(length + 1);
18604
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
18605
                g.ClipboardHandlerData[length] = 0;
18606
                CFRelease(cf_data);
18607
                return g.ClipboardHandlerData.Data;
18608
            }
18609
        }
18610
    }
18611
    return NULL;
18612
}
18613
18614
#else
18615
18616
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
18617
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18618
0
{
18619
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18620
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
18621
0
}
18622
18623
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
18624
0
{
18625
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18626
0
    g.ClipboardHandlerData.clear();
18627
0
    const char* text_end = text + strlen(text);
18628
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
18629
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
18630
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
18631
0
}
18632
18633
#endif
18634
18635
// Win32 API IME support (for Asian languages, etc.)
18636
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
18637
18638
#include <imm.h>
18639
#ifdef _MSC_VER
18640
#pragma comment(lib, "imm32")
18641
#endif
18642
18643
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
18644
{
18645
    // Notify OS Input Method Editor of text input position
18646
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
18647
    if (hwnd == 0)
18648
        return;
18649
18650
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
18651
    if (HIMC himc = ::ImmGetContext(hwnd))
18652
    {
18653
        COMPOSITIONFORM composition_form = {};
18654
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18655
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18656
        composition_form.dwStyle = CFS_FORCE_POSITION;
18657
        ::ImmSetCompositionWindow(himc, &composition_form);
18658
        CANDIDATEFORM candidate_form = {};
18659
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
18660
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18661
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18662
        ::ImmSetCandidateWindow(himc, &candidate_form);
18663
        ::ImmReleaseContext(hwnd, himc);
18664
    }
18665
}
18666
18667
#else
18668
18669
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
18670
18671
#endif
18672
18673
//-----------------------------------------------------------------------------
18674
// [SECTION] METRICS/DEBUGGER WINDOW
18675
//-----------------------------------------------------------------------------
18676
// - RenderViewportThumbnail() [Internal]
18677
// - RenderViewportsThumbnails() [Internal]
18678
// - DebugTextEncoding()
18679
// - MetricsHelpMarker() [Internal]
18680
// - ShowFontAtlas() [Internal]
18681
// - ShowMetricsWindow()
18682
// - DebugNodeColumns() [Internal]
18683
// - DebugNodeDockNode() [Internal]
18684
// - DebugNodeDrawList() [Internal]
18685
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
18686
// - DebugNodeFont() [Internal]
18687
// - DebugNodeFontGlyph() [Internal]
18688
// - DebugNodeStorage() [Internal]
18689
// - DebugNodeTabBar() [Internal]
18690
// - DebugNodeViewport() [Internal]
18691
// - DebugNodeWindow() [Internal]
18692
// - DebugNodeWindowSettings() [Internal]
18693
// - DebugNodeWindowsList() [Internal]
18694
// - DebugNodeWindowsListByBeginStackParent() [Internal]
18695
//-----------------------------------------------------------------------------
18696
18697
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
18698
18699
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
18700
0
{
18701
0
    ImGuiContext& g = *GImGui;
18702
0
    ImGuiWindow* window = g.CurrentWindow;
18703
18704
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
18705
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
18706
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f;
18707
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
18708
0
    for (int i = 0; i != g.Windows.Size; i++)
18709
0
    {
18710
0
        ImGuiWindow* thumb_window = g.Windows[i];
18711
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
18712
0
            continue;
18713
0
        if (thumb_window->Viewport != viewport)
18714
0
            continue;
18715
18716
0
        ImRect thumb_r = thumb_window->Rect();
18717
0
        ImRect title_r = thumb_window->TitleBarRect();
18718
0
        thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off +  thumb_r.Max * scale));
18719
0
        title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
18720
0
        thumb_r.ClipWithFull(bb);
18721
0
        title_r.ClipWithFull(bb);
18722
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
18723
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
18724
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
18725
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18726
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
18727
0
    }
18728
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18729
0
}
18730
18731
static void RenderViewportsThumbnails()
18732
0
{
18733
0
    ImGuiContext& g = *GImGui;
18734
0
    ImGuiWindow* window = g.CurrentWindow;
18735
18736
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
18737
0
    float SCALE = 1.0f / 8.0f;
18738
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
18739
0
    for (int n = 0; n < g.Viewports.Size; n++)
18740
0
        bb_full.Add(g.Viewports[n]->GetMainRect());
18741
0
    ImVec2 p = window->DC.CursorPos;
18742
0
    ImVec2 off = p - bb_full.Min * SCALE;
18743
0
    for (int n = 0; n < g.Viewports.Size; n++)
18744
0
    {
18745
0
        ImGuiViewportP* viewport = g.Viewports[n];
18746
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
18747
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
18748
0
    }
18749
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
18750
0
}
18751
18752
static int IMGUI_CDECL ViewportComparerByFrontMostStampCount(const void* lhs, const void* rhs)
18753
0
{
18754
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
18755
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
18756
0
    return b->LastFrontMostStampCount - a->LastFrontMostStampCount;
18757
0
}
18758
18759
// Draw an arbitrary US keyboard layout to visualize translated keys
18760
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
18761
0
{
18762
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
18763
0
    const float  key_rounding = 3.0f;
18764
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
18765
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
18766
0
    const float  key_face_rounding = 2.0f;
18767
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
18768
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
18769
0
    const float  key_row_offset = 9.0f;
18770
18771
0
    ImVec2 board_min = GetCursorScreenPos();
18772
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
18773
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
18774
18775
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
18776
0
    const KeyLayoutData keys_to_display[] =
18777
0
    {
18778
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
18779
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
18780
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
18781
0
    };
18782
18783
    // Elements rendered manually via ImDrawList API are not clipped automatically.
18784
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
18785
0
    Dummy(board_max - board_min);
18786
0
    if (!IsItemVisible())
18787
0
        return;
18788
0
    draw_list->PushClipRect(board_min, board_max, true);
18789
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
18790
0
    {
18791
0
        const KeyLayoutData* key_data = &keys_to_display[n];
18792
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
18793
0
        ImVec2 key_max = key_min + key_size;
18794
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
18795
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
18796
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
18797
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
18798
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
18799
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
18800
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
18801
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
18802
0
        if (ImGui::IsKeyDown(key_data->Key))
18803
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
18804
0
    }
18805
0
    draw_list->PopClipRect();
18806
0
}
18807
18808
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
18809
void ImGui::DebugTextEncoding(const char* str)
18810
0
{
18811
0
    Text("Text: \"%s\"", str);
18812
0
    if (!BeginTable("list", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit))
18813
0
        return;
18814
0
    TableSetupColumn("Offset");
18815
0
    TableSetupColumn("UTF-8");
18816
0
    TableSetupColumn("Glyph");
18817
0
    TableSetupColumn("Codepoint");
18818
0
    TableHeadersRow();
18819
0
    for (const char* p = str; *p != 0; )
18820
0
    {
18821
0
        unsigned int c;
18822
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
18823
0
        TableNextColumn();
18824
0
        Text("%d", (int)(p - str));
18825
0
        TableNextColumn();
18826
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
18827
0
        {
18828
0
            if (byte_index > 0)
18829
0
                SameLine();
18830
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
18831
0
        }
18832
0
        TableNextColumn();
18833
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
18834
0
            TextUnformatted(p, p + c_utf8_len);
18835
0
        else
18836
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
18837
0
        TableNextColumn();
18838
0
        Text("U+%04X", (int)c);
18839
0
        p += c_utf8_len;
18840
0
    }
18841
0
    EndTable();
18842
0
}
18843
18844
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
18845
static void MetricsHelpMarker(const char* desc)
18846
0
{
18847
0
    ImGui::TextDisabled("(?)");
18848
0
    if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort) && ImGui::BeginTooltip())
18849
0
    {
18850
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
18851
0
        ImGui::TextUnformatted(desc);
18852
0
        ImGui::PopTextWrapPos();
18853
0
        ImGui::EndTooltip();
18854
0
    }
18855
0
}
18856
18857
// [DEBUG] List fonts in a font atlas and display its texture
18858
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
18859
0
{
18860
0
    for (int i = 0; i < atlas->Fonts.Size; i++)
18861
0
    {
18862
0
        ImFont* font = atlas->Fonts[i];
18863
0
        PushID(font);
18864
0
        DebugNodeFont(font);
18865
0
        PopID();
18866
0
    }
18867
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
18868
0
    {
18869
0
        ImGuiContext& g = *GImGui;
18870
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
18871
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
18872
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
18873
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
18874
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
18875
0
        TreePop();
18876
0
    }
18877
0
}
18878
18879
void ImGui::ShowMetricsWindow(bool* p_open)
18880
0
{
18881
0
    ImGuiContext& g = *GImGui;
18882
0
    ImGuiIO& io = g.IO;
18883
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
18884
0
    if (cfg->ShowDebugLog)
18885
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
18886
0
    if (cfg->ShowStackTool)
18887
0
        ShowStackToolWindow(&cfg->ShowStackTool);
18888
18889
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
18890
0
    {
18891
0
        End();
18892
0
        return;
18893
0
    }
18894
18895
    // Basic info
18896
0
    Text("Dear ImGui %s", GetVersion());
18897
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
18898
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
18899
0
    Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
18900
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
18901
18902
0
    Separator();
18903
18904
    // Debugging enums
18905
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
18906
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
18907
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
18908
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
18909
0
    if (cfg->ShowWindowsRectsType < 0)
18910
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
18911
0
    if (cfg->ShowTablesRectsType < 0)
18912
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
18913
18914
0
    struct Funcs
18915
0
    {
18916
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
18917
0
        {
18918
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
18919
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
18920
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
18921
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
18922
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
18923
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
18924
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
18925
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
18926
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
18927
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
18928
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); } // Note: y1/y2 not always accurate
18929
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
18930
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
18931
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
18932
0
            IM_ASSERT(0);
18933
0
            return ImRect();
18934
0
        }
18935
18936
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
18937
0
        {
18938
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
18939
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
18940
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
18941
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
18942
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
18943
0
            else if (rect_type == WRT_Content)       { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
18944
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
18945
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
18946
0
            IM_ASSERT(0);
18947
0
            return ImRect();
18948
0
        }
18949
0
    };
18950
18951
    // Tools
18952
0
    if (TreeNode("Tools"))
18953
0
    {
18954
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
18955
0
        SameLine();
18956
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
18957
0
        if (show_encoding_viewer)
18958
0
        {
18959
0
            static char buf[100] = "";
18960
0
            SetNextItemWidth(-FLT_MIN);
18961
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
18962
0
            if (buf[0] != 0)
18963
0
                DebugTextEncoding(buf);
18964
0
            TreePop();
18965
0
        }
18966
18967
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
18968
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
18969
0
            DebugStartItemPicker();
18970
0
        SameLine();
18971
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
18972
18973
        // Stack Tool is your best friend!
18974
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
18975
0
        SameLine();
18976
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
18977
18978
        // Stack Tool is your best friend!
18979
0
        Checkbox("Show Stack Tool", &cfg->ShowStackTool);
18980
0
        SameLine();
18981
0
        MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
18982
18983
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
18984
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
18985
0
        SameLine();
18986
0
        SetNextItemWidth(GetFontSize() * 12);
18987
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
18988
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
18989
0
        {
18990
0
            BulletText("'%s':", g.NavWindow->Name);
18991
0
            Indent();
18992
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
18993
0
            {
18994
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
18995
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
18996
0
            }
18997
0
            Unindent();
18998
0
        }
18999
19000
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
19001
0
        SameLine();
19002
0
        SetNextItemWidth(GetFontSize() * 12);
19003
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
19004
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
19005
0
        {
19006
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19007
0
            {
19008
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19009
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
19010
0
                    continue;
19011
19012
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
19013
0
                if (IsItemHovered())
19014
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19015
0
                Indent();
19016
0
                char buf[128];
19017
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
19018
0
                {
19019
0
                    if (rect_n >= TRT_ColumnsRect)
19020
0
                    {
19021
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
19022
0
                            continue;
19023
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19024
0
                        {
19025
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
19026
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
19027
0
                            Selectable(buf);
19028
0
                            if (IsItemHovered())
19029
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19030
0
                        }
19031
0
                    }
19032
0
                    else
19033
0
                    {
19034
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
19035
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
19036
0
                        Selectable(buf);
19037
0
                        if (IsItemHovered())
19038
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19039
0
                    }
19040
0
                }
19041
0
                Unindent();
19042
0
            }
19043
0
        }
19044
19045
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
19046
0
        SameLine();
19047
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
19048
19049
0
        TreePop();
19050
0
    }
19051
19052
    // Windows
19053
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
19054
0
    {
19055
        //SetNextItemOpen(true, ImGuiCond_Once);
19056
0
        DebugNodeWindowsList(&g.Windows, "By display order");
19057
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
19058
0
        if (TreeNode("By submission order (begin stack)"))
19059
0
        {
19060
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
19061
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
19062
0
            temp_buffer.resize(0);
19063
0
            for (int i = 0; i < g.Windows.Size; i++)
19064
0
                if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)
19065
0
                    temp_buffer.push_back(g.Windows[i]);
19066
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
19067
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
19068
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
19069
0
            TreePop();
19070
0
        }
19071
19072
0
        TreePop();
19073
0
    }
19074
19075
    // DrawLists
19076
0
    int drawlist_count = 0;
19077
0
    for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
19078
0
        drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
19079
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
19080
0
    {
19081
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
19082
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
19083
0
        for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
19084
0
        {
19085
0
            ImGuiViewportP* viewport = g.Viewports[viewport_i];
19086
0
            bool viewport_has_drawlist = false;
19087
0
            for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
19088
0
                for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
19089
0
                {
19090
0
                    if (!viewport_has_drawlist)
19091
0
                        Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
19092
0
                    viewport_has_drawlist = true;
19093
0
                    DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
19094
0
                }
19095
0
        }
19096
0
        TreePop();
19097
0
    }
19098
19099
    // Viewports
19100
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
19101
0
    {
19102
0
        Indent(GetTreeNodeToLabelSpacing());
19103
0
        RenderViewportsThumbnails();
19104
0
        Unindent(GetTreeNodeToLabelSpacing());
19105
19106
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
19107
0
        SameLine();
19108
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
19109
0
        if (open)
19110
0
        {
19111
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
19112
0
            {
19113
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
19114
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
19115
0
                    i, mon.DpiScale * 100.0f,
19116
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
19117
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
19118
0
            }
19119
0
            TreePop();
19120
0
        }
19121
19122
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19123
0
        if (TreeNode("Inferred Z order (front-to-back)"))
19124
0
        {
19125
0
            static ImVector<ImGuiViewportP*> viewports;
19126
0
            viewports.resize(g.Viewports.Size);
19127
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
19128
0
            if (viewports.Size > 1)
19129
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByFrontMostStampCount);
19130
0
            for (int i = 0; i < viewports.Size; i++)
19131
0
                BulletText("Viewport #%d, ID: 0x%08X, FrontMostStampCount = %08d, Window: \"%s\"", viewports[i]->Idx, viewports[i]->ID, viewports[i]->LastFrontMostStampCount, viewports[i]->Window ? viewports[i]->Window->Name : "N/A");
19132
0
            TreePop();
19133
0
        }
19134
19135
0
        for (int i = 0; i < g.Viewports.Size; i++)
19136
0
            DebugNodeViewport(g.Viewports[i]);
19137
0
        TreePop();
19138
0
    }
19139
19140
    // Details for Popups
19141
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
19142
0
    {
19143
0
        for (int i = 0; i < g.OpenPopupStack.Size; i++)
19144
0
        {
19145
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
19146
0
            const ImGuiPopupData* popup_data = &g.OpenPopupStack[i];
19147
0
            ImGuiWindow* window = popup_data->Window;
19148
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
19149
0
                popup_data->PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
19150
0
                popup_data->BackupNavWindow ? popup_data->BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
19151
0
        }
19152
0
        TreePop();
19153
0
    }
19154
19155
    // Details for TabBars
19156
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
19157
0
    {
19158
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
19159
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
19160
0
            {
19161
0
                PushID(tab_bar);
19162
0
                DebugNodeTabBar(tab_bar, "TabBar");
19163
0
                PopID();
19164
0
            }
19165
0
        TreePop();
19166
0
    }
19167
19168
    // Details for Tables
19169
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
19170
0
    {
19171
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
19172
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
19173
0
                DebugNodeTable(table);
19174
0
        TreePop();
19175
0
    }
19176
19177
    // Details for Fonts
19178
0
    ImFontAtlas* atlas = g.IO.Fonts;
19179
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
19180
0
    {
19181
0
        ShowFontAtlas(atlas);
19182
0
        TreePop();
19183
0
    }
19184
19185
    // Details for InputText
19186
0
    if (TreeNode("InputText"))
19187
0
    {
19188
0
        DebugNodeInputTextState(&g.InputTextState);
19189
0
        TreePop();
19190
0
    }
19191
19192
    // Details for Docking
19193
0
#ifdef IMGUI_HAS_DOCK
19194
0
    if (TreeNode("Docking"))
19195
0
    {
19196
0
        static bool root_nodes_only = true;
19197
0
        ImGuiDockContext* dc = &g.DockContext;
19198
0
        Checkbox("List root nodes", &root_nodes_only);
19199
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
19200
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
19201
0
        SameLine();
19202
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
19203
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
19204
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19205
0
                if (!root_nodes_only || node->IsRootNode())
19206
0
                    DebugNodeDockNode(node, "Node");
19207
0
        TreePop();
19208
0
    }
19209
0
#endif // #ifdef IMGUI_HAS_DOCK
19210
19211
    // Settings
19212
0
    if (TreeNode("Settings"))
19213
0
    {
19214
0
        if (SmallButton("Clear"))
19215
0
            ClearIniSettings();
19216
0
        SameLine();
19217
0
        if (SmallButton("Save to memory"))
19218
0
            SaveIniSettingsToMemory();
19219
0
        SameLine();
19220
0
        if (SmallButton("Save to disk"))
19221
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
19222
0
        SameLine();
19223
0
        if (g.IO.IniFilename)
19224
0
            Text("\"%s\"", g.IO.IniFilename);
19225
0
        else
19226
0
            TextUnformatted("<NULL>");
19227
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
19228
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
19229
0
        {
19230
0
            for (int n = 0; n < g.SettingsHandlers.Size; n++)
19231
0
                BulletText("%s", g.SettingsHandlers[n].TypeName);
19232
0
            TreePop();
19233
0
        }
19234
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19235
0
        {
19236
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19237
0
                DebugNodeWindowSettings(settings);
19238
0
            TreePop();
19239
0
        }
19240
19241
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19242
0
        {
19243
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19244
0
                DebugNodeTableSettings(settings);
19245
0
            TreePop();
19246
0
        }
19247
19248
0
#ifdef IMGUI_HAS_DOCK
19249
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19250
0
        {
19251
0
            ImGuiDockContext* dc = &g.DockContext;
19252
0
            Text("In SettingsWindows:");
19253
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19254
0
                if (settings->DockId != 0)
19255
0
                    BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId);
19256
0
            Text("In SettingsNodes:");
19257
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19258
0
            {
19259
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19260
0
                const char* selected_tab_name = NULL;
19261
0
                if (settings->SelectedTabId)
19262
0
                {
19263
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19264
0
                        selected_tab_name = window->Name;
19265
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
19266
0
                        selected_tab_name = window_settings->GetName();
19267
0
                }
19268
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19269
0
            }
19270
0
            TreePop();
19271
0
        }
19272
0
#endif // #ifdef IMGUI_HAS_DOCK
19273
19274
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19275
0
        {
19276
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19277
0
            TreePop();
19278
0
        }
19279
0
        TreePop();
19280
0
    }
19281
19282
0
    if (TreeNode("Inputs"))
19283
0
    {
19284
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19285
0
        {
19286
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19287
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
19288
0
            Indent();
19289
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19290
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19291
#else
19292
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19293
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19294
#endif
19295
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19296
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19297
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19298
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19299
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19300
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19301
0
            Unindent();
19302
0
        }
19303
19304
0
        Text("MOUSE STATE");
19305
0
        {
19306
0
            Indent();
19307
0
            if (IsMousePosValid())
19308
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19309
0
            else
19310
0
                Text("Mouse pos: <INVALID>");
19311
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19312
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19313
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19314
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19315
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19316
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19317
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19318
0
            Unindent();
19319
0
        }
19320
19321
0
        Text("MOUSE WHEELING");
19322
0
        {
19323
0
            Indent();
19324
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19325
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19326
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19327
0
            Unindent();
19328
0
        }
19329
19330
0
        Text("KEY OWNERS");
19331
0
        {
19332
0
            Indent();
19333
0
            if (BeginListBox("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19334
0
            {
19335
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19336
0
                {
19337
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
19338
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
19339
0
                        continue;
19340
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
19341
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
19342
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
19343
0
                }
19344
0
                EndListBox();
19345
0
            }
19346
0
            Unindent();
19347
0
        }
19348
0
        Text("SHORTCUT ROUTING");
19349
0
        {
19350
0
            Indent();
19351
0
            if (BeginListBox("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19352
0
            {
19353
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19354
0
                {
19355
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
19356
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
19357
0
                    {
19358
0
                        char key_chord_name[64];
19359
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
19360
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
19361
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
19362
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
19363
0
                        idx = routing_data->NextEntryIndex;
19364
0
                    }
19365
0
                }
19366
0
                EndListBox();
19367
0
            }
19368
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19369
0
            Unindent();
19370
0
        }
19371
0
        TreePop();
19372
0
    }
19373
19374
0
    if (TreeNode("Internal state"))
19375
0
    {
19376
0
        Text("WINDOWING");
19377
0
        Indent();
19378
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
19379
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
19380
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
19381
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
19382
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
19383
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19384
0
        Unindent();
19385
19386
0
        Text("ITEMS");
19387
0
        Indent();
19388
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
19389
0
        DebugLocateItemOnHover(g.ActiveId);
19390
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
19391
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19392
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
19393
0
        Text("HoverDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverDelayId, g.HoverDelayTimer, g.HoverDelayClearTimer);
19394
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
19395
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
19396
0
        Unindent();
19397
19398
0
        Text("NAV,FOCUS");
19399
0
        Indent();
19400
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
19401
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
19402
0
        DebugLocateItemOnHover(g.NavId);
19403
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
19404
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
19405
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
19406
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
19407
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
19408
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
19409
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
19410
0
        Unindent();
19411
19412
0
        TreePop();
19413
0
    }
19414
19415
    // Overlay: Display windows Rectangles and Begin Order
19416
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
19417
0
    {
19418
0
        for (int n = 0; n < g.Windows.Size; n++)
19419
0
        {
19420
0
            ImGuiWindow* window = g.Windows[n];
19421
0
            if (!window->WasActive)
19422
0
                continue;
19423
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
19424
0
            if (cfg->ShowWindowsRects)
19425
0
            {
19426
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
19427
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19428
0
            }
19429
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
19430
0
            {
19431
0
                char buf[32];
19432
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
19433
0
                float font_size = GetFontSize();
19434
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
19435
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
19436
0
            }
19437
0
        }
19438
0
    }
19439
19440
    // Overlay: Display Tables Rectangles
19441
0
    if (cfg->ShowTablesRects)
19442
0
    {
19443
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19444
0
        {
19445
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19446
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
19447
0
                continue;
19448
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
19449
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
19450
0
            {
19451
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19452
0
                {
19453
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
19454
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
19455
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
19456
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
19457
0
                }
19458
0
            }
19459
0
            else
19460
0
            {
19461
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
19462
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19463
0
            }
19464
0
        }
19465
0
    }
19466
19467
0
#ifdef IMGUI_HAS_DOCK
19468
    // Overlay: Display Docking info
19469
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
19470
0
    {
19471
0
        char buf[64] = "";
19472
0
        char* p = buf;
19473
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
19474
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19475
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
19476
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
19477
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
19478
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
19479
0
        int depth = DockNodeGetDepth(node);
19480
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
19481
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
19482
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
19483
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
19484
0
    }
19485
0
#endif // #ifdef IMGUI_HAS_DOCK
19486
19487
0
    End();
19488
0
}
19489
19490
// [DEBUG] Display contents of Columns
19491
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
19492
0
{
19493
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
19494
0
        return;
19495
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
19496
0
    for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
19497
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
19498
0
    TreePop();
19499
0
}
19500
19501
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
19502
0
{
19503
0
    using namespace ImGui;
19504
0
    PushID(label);
19505
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
19506
0
    Text("%s:", label);
19507
0
    if (!enabled)
19508
0
        BeginDisabled();
19509
0
    CheckboxFlags("NoSplit", p_flags, ImGuiDockNodeFlags_NoSplit);
19510
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
19511
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
19512
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
19513
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
19514
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
19515
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
19516
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
19517
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking);
19518
0
    CheckboxFlags("NoDockingSplitMe", p_flags, ImGuiDockNodeFlags_NoDockingSplitMe);
19519
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
19520
0
    CheckboxFlags("NoDockingOverMe", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
19521
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
19522
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
19523
0
    if (!enabled)
19524
0
        EndDisabled();
19525
0
    PopStyleVar();
19526
0
    PopID();
19527
0
}
19528
19529
// [DEBUG] Display contents of ImDockNode
19530
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
19531
0
{
19532
0
    ImGuiContext& g = *GImGui;
19533
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
19534
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
19535
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19536
0
    bool open;
19537
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19538
0
    if (node->Windows.Size > 0)
19539
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19540
0
    else
19541
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19542
0
    if (!is_alive) { PopStyleColor(); }
19543
0
    if (is_active && IsItemHovered())
19544
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
19545
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
19546
0
    if (open)
19547
0
    {
19548
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
19549
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
19550
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
19551
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
19552
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
19553
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
19554
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
19555
0
        BulletText("Misc:%s%s%s%s%s%s%s",
19556
0
            node->IsDockSpace() ? " IsDockSpace" : "",
19557
0
            node->IsCentralNode() ? " IsCentralNode" : "",
19558
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
19559
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
19560
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
19561
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
19562
0
        {
19563
0
            if (BeginTable("flags", 4))
19564
0
            {
19565
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
19566
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
19567
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
19568
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
19569
0
                EndTable();
19570
0
            }
19571
0
            TreePop();
19572
0
        }
19573
0
        if (node->ParentNode)
19574
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
19575
0
        if (node->ChildNodes[0])
19576
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
19577
0
        if (node->ChildNodes[1])
19578
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
19579
0
        if (node->TabBar)
19580
0
            DebugNodeTabBar(node->TabBar, "TabBar");
19581
0
        DebugNodeWindowsList(&node->Windows, "Windows");
19582
19583
0
        TreePop();
19584
0
    }
19585
0
}
19586
19587
// [DEBUG] Display contents of ImDrawList
19588
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
19589
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
19590
0
{
19591
0
    ImGuiContext& g = *GImGui;
19592
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19593
0
    int cmd_count = draw_list->CmdBuffer.Size;
19594
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
19595
0
        cmd_count--;
19596
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
19597
0
    if (draw_list == GetWindowDrawList())
19598
0
    {
19599
0
        SameLine();
19600
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
19601
0
        if (node_open)
19602
0
            TreePop();
19603
0
        return;
19604
0
    }
19605
19606
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
19607
0
    if (window && IsItemHovered() && fg_draw_list)
19608
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19609
0
    if (!node_open)
19610
0
        return;
19611
19612
0
    if (window && !window->WasActive)
19613
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
19614
19615
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
19616
0
    {
19617
0
        if (pcmd->UserCallback)
19618
0
        {
19619
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
19620
0
            continue;
19621
0
        }
19622
19623
0
        char buf[300];
19624
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
19625
0
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
19626
0
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
19627
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
19628
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
19629
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
19630
0
        if (!pcmd_node_open)
19631
0
            continue;
19632
19633
        // Calculate approximate coverage area (touched pixel count)
19634
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
19635
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
19636
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
19637
0
        float total_area = 0.0f;
19638
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
19639
0
        {
19640
0
            ImVec2 triangle[3];
19641
0
            for (int n = 0; n < 3; n++, idx_n++)
19642
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
19643
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
19644
0
        }
19645
19646
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
19647
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
19648
0
        Selectable(buf);
19649
0
        if (IsItemHovered() && fg_draw_list)
19650
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
19651
19652
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
19653
0
        ImGuiListClipper clipper;
19654
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
19655
0
        while (clipper.Step())
19656
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
19657
0
            {
19658
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
19659
0
                ImVec2 triangle[3];
19660
0
                for (int n = 0; n < 3; n++, idx_i++)
19661
0
                {
19662
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
19663
0
                    triangle[n] = v.pos;
19664
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
19665
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
19666
0
                }
19667
19668
0
                Selectable(buf, false);
19669
0
                if (fg_draw_list && IsItemHovered())
19670
0
                {
19671
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
19672
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19673
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
19674
0
                    fg_draw_list->Flags = backup_flags;
19675
0
                }
19676
0
            }
19677
0
        TreePop();
19678
0
    }
19679
0
    TreePop();
19680
0
}
19681
19682
// [DEBUG] Display mesh/aabb of a ImDrawCmd
19683
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
19684
0
{
19685
0
    IM_ASSERT(show_mesh || show_aabb);
19686
19687
    // Draw wire-frame version of all triangles
19688
0
    ImRect clip_rect = draw_cmd->ClipRect;
19689
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19690
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
19691
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19692
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
19693
0
    {
19694
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
19695
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
19696
19697
0
        ImVec2 triangle[3];
19698
0
        for (int n = 0; n < 3; n++, idx_n++)
19699
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
19700
0
        if (show_mesh)
19701
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
19702
0
    }
19703
    // Draw bounding boxes
19704
0
    if (show_aabb)
19705
0
    {
19706
0
        out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
19707
0
        out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
19708
0
    }
19709
0
    out_draw_list->Flags = backup_flags;
19710
0
}
19711
19712
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
19713
void ImGui::DebugNodeFont(ImFont* font)
19714
0
{
19715
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
19716
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
19717
0
    SameLine();
19718
0
    if (SmallButton("Set as default"))
19719
0
        GetIO().FontDefault = font;
19720
0
    if (!opened)
19721
0
        return;
19722
19723
    // Display preview text
19724
0
    PushFont(font);
19725
0
    Text("The quick brown fox jumps over the lazy dog");
19726
0
    PopFont();
19727
19728
    // Display details
19729
0
    SetNextItemWidth(GetFontSize() * 8);
19730
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
19731
0
    SameLine(); MetricsHelpMarker(
19732
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
19733
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
19734
0
        "You may oversample them to get some flexibility with scaling. "
19735
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
19736
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
19737
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
19738
0
    char c_str[5];
19739
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
19740
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
19741
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
19742
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
19743
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
19744
0
        if (font->ConfigData)
19745
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
19746
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
19747
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
19748
19749
    // Display all glyphs of the fonts in separate pages of 256 characters
19750
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
19751
0
    {
19752
0
        ImDrawList* draw_list = GetWindowDrawList();
19753
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
19754
0
        const float cell_size = font->FontSize * 1;
19755
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
19756
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
19757
0
        {
19758
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
19759
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
19760
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
19761
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
19762
0
            {
19763
0
                base += 4096 - 256;
19764
0
                continue;
19765
0
            }
19766
19767
0
            int count = 0;
19768
0
            for (unsigned int n = 0; n < 256; n++)
19769
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
19770
0
                    count++;
19771
0
            if (count <= 0)
19772
0
                continue;
19773
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
19774
0
                continue;
19775
19776
            // Draw a 16x16 grid of glyphs
19777
0
            ImVec2 base_pos = GetCursorScreenPos();
19778
0
            for (unsigned int n = 0; n < 256; n++)
19779
0
            {
19780
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
19781
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
19782
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
19783
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
19784
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
19785
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
19786
0
                if (!glyph)
19787
0
                    continue;
19788
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
19789
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
19790
0
                {
19791
0
                    DebugNodeFontGlyph(font, glyph);
19792
0
                    EndTooltip();
19793
0
                }
19794
0
            }
19795
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
19796
0
            TreePop();
19797
0
        }
19798
0
        TreePop();
19799
0
    }
19800
0
    TreePop();
19801
0
}
19802
19803
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
19804
0
{
19805
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
19806
0
    Separator();
19807
0
    Text("Visible: %d", glyph->Visible);
19808
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
19809
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
19810
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
19811
0
}
19812
19813
// [DEBUG] Display contents of ImGuiStorage
19814
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
19815
0
{
19816
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
19817
0
        return;
19818
0
    for (int n = 0; n < storage->Data.Size; n++)
19819
0
    {
19820
0
        const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
19821
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
19822
0
    }
19823
0
    TreePop();
19824
0
}
19825
19826
// [DEBUG] Display contents of ImGuiTabBar
19827
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
19828
0
{
19829
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
19830
0
    char buf[256];
19831
0
    char* p = buf;
19832
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
19833
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
19834
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
19835
0
    p += ImFormatString(p, buf_end - p, "  { ");
19836
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
19837
0
    {
19838
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19839
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
19840
0
    }
19841
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
19842
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19843
0
    bool open = TreeNode(label, "%s", buf);
19844
0
    if (!is_active) { PopStyleColor(); }
19845
0
    if (is_active && IsItemHovered())
19846
0
    {
19847
0
        ImDrawList* draw_list = GetForegroundDrawList();
19848
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
19849
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19850
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19851
0
    }
19852
0
    if (open)
19853
0
    {
19854
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
19855
0
        {
19856
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19857
0
            PushID(tab);
19858
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
19859
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
19860
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
19861
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
19862
0
            PopID();
19863
0
        }
19864
0
        TreePop();
19865
0
    }
19866
0
}
19867
19868
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
19869
0
{
19870
0
    SetNextItemOpen(true, ImGuiCond_Once);
19871
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
19872
0
    {
19873
0
        ImGuiWindowFlags flags = viewport->Flags;
19874
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
19875
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
19876
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
19877
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
19878
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
19879
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
19880
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
19881
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
19882
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
19883
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
19884
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
19885
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
19886
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
19887
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
19888
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
19889
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
19890
0
            (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "",
19891
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
19892
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
19893
0
        for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
19894
0
            for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
19895
0
                DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
19896
0
        TreePop();
19897
0
    }
19898
0
}
19899
19900
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
19901
0
{
19902
0
    if (window == NULL)
19903
0
    {
19904
0
        BulletText("%s: NULL", label);
19905
0
        return;
19906
0
    }
19907
19908
0
    ImGuiContext& g = *GImGui;
19909
0
    const bool is_active = window->WasActive;
19910
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19911
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19912
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
19913
0
    if (!is_active) { PopStyleColor(); }
19914
0
    if (IsItemHovered() && is_active)
19915
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19916
0
    if (!open)
19917
0
        return;
19918
19919
0
    if (window->MemoryCompacted)
19920
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
19921
19922
0
    ImGuiWindowFlags flags = window->Flags;
19923
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
19924
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
19925
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
19926
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
19927
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
19928
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
19929
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
19930
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
19931
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
19932
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
19933
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
19934
0
    {
19935
0
        ImRect r = window->NavRectRel[layer];
19936
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
19937
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
19938
0
        else
19939
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
19940
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
19941
0
    }
19942
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
19943
19944
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
19945
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
19946
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
19947
0
    if (window->DockNode || window->DockNodeAsHost)
19948
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
19949
19950
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
19951
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
19952
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
19953
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
19954
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
19955
0
    {
19956
0
        for (int n = 0; n < window->ColumnsStorage.Size; n++)
19957
0
            DebugNodeColumns(&window->ColumnsStorage[n]);
19958
0
        TreePop();
19959
0
    }
19960
0
    DebugNodeStorage(&window->StateStorage, "Storage");
19961
0
    TreePop();
19962
0
}
19963
19964
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
19965
0
{
19966
0
    if (settings->WantDelete)
19967
0
        BeginDisabled();
19968
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
19969
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
19970
0
    if (settings->WantDelete)
19971
0
        EndDisabled();
19972
0
}
19973
19974
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
19975
0
{
19976
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
19977
0
        return;
19978
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
19979
0
    {
19980
0
        PushID((*windows)[i]);
19981
0
        DebugNodeWindow((*windows)[i], "Window");
19982
0
        PopID();
19983
0
    }
19984
0
    TreePop();
19985
0
}
19986
19987
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
19988
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
19989
0
{
19990
0
    for (int i = 0; i < windows_size; i++)
19991
0
    {
19992
0
        ImGuiWindow* window = windows[i];
19993
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
19994
0
            continue;
19995
0
        char buf[20];
19996
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
19997
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
19998
0
        DebugNodeWindow(window, buf);
19999
0
        Indent();
20000
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
20001
0
        Unindent();
20002
0
    }
20003
0
}
20004
20005
//-----------------------------------------------------------------------------
20006
// [SECTION] DEBUG LOG WINDOW
20007
//-----------------------------------------------------------------------------
20008
20009
void ImGui::DebugLog(const char* fmt, ...)
20010
0
{
20011
0
    va_list args;
20012
0
    va_start(args, fmt);
20013
0
    DebugLogV(fmt, args);
20014
0
    va_end(args);
20015
0
}
20016
20017
void ImGui::DebugLogV(const char* fmt, va_list args)
20018
0
{
20019
0
    ImGuiContext& g = *GImGui;
20020
0
    const int old_size = g.DebugLogBuf.size();
20021
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
20022
0
    g.DebugLogBuf.appendfv(fmt, args);
20023
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
20024
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
20025
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
20026
0
}
20027
20028
void ImGui::ShowDebugLogWindow(bool* p_open)
20029
0
{
20030
0
    ImGuiContext& g = *GImGui;
20031
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20032
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
20033
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
20034
0
    {
20035
0
        End();
20036
0
        return;
20037
0
    }
20038
20039
0
    AlignTextToFramePadding();
20040
0
    Text("Log events:");
20041
0
    SameLine(); CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
20042
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
20043
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
20044
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
20045
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
20046
0
    SameLine(); if (CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper)) { g.DebugLogClipperAutoDisableFrames = 2; } if (IsItemHovered()) SetTooltip("Clipper log auto-disabled after 2 frames");
20047
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
20048
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
20049
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
20050
20051
0
    if (SmallButton("Clear"))
20052
0
    {
20053
0
        g.DebugLogBuf.clear();
20054
0
        g.DebugLogIndex.clear();
20055
0
    }
20056
0
    SameLine();
20057
0
    if (SmallButton("Copy"))
20058
0
        SetClipboardText(g.DebugLogBuf.c_str());
20059
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
20060
20061
0
    ImGuiListClipper clipper;
20062
0
    clipper.Begin(g.DebugLogIndex.size());
20063
0
    while (clipper.Step())
20064
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
20065
0
        {
20066
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
20067
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
20068
0
            TextUnformatted(line_begin, line_end);
20069
0
            ImRect text_rect = g.LastItemData.Rect;
20070
0
            if (IsItemHovered())
20071
0
                for (const char* p = line_begin; p < line_end - 10; p++)
20072
0
                {
20073
0
                    ImGuiID id = 0;
20074
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
20075
0
                        continue;
20076
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
20077
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
20078
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
20079
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
20080
0
                        DebugLocateItemOnHover(id);
20081
0
                    p += 10;
20082
0
                }
20083
0
        }
20084
0
    if (GetScrollY() >= GetScrollMaxY())
20085
0
        SetScrollHereY(1.0f);
20086
0
    EndChild();
20087
20088
0
    End();
20089
0
}
20090
20091
//-----------------------------------------------------------------------------
20092
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
20093
//-----------------------------------------------------------------------------
20094
20095
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
20096
20097
void ImGui::DebugLocateItem(ImGuiID target_id)
20098
0
{
20099
0
    ImGuiContext& g = *GImGui;
20100
0
    g.DebugLocateId = target_id;
20101
0
    g.DebugLocateFrames = 2;
20102
0
}
20103
20104
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
20105
0
{
20106
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
20107
0
        return;
20108
0
    ImGuiContext& g = *GImGui;
20109
0
    DebugLocateItem(target_id);
20110
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
20111
0
}
20112
20113
void ImGui::DebugLocateItemResolveWithLastItem()
20114
0
{
20115
0
    ImGuiContext& g = *GImGui;
20116
0
    ImGuiLastItemData item_data = g.LastItemData;
20117
0
    g.DebugLocateId = 0;
20118
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
20119
0
    ImRect r = item_data.Rect;
20120
0
    r.Expand(3.0f);
20121
0
    ImVec2 p1 = g.IO.MousePos;
20122
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
20123
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
20124
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
20125
0
}
20126
20127
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
20128
void ImGui::UpdateDebugToolItemPicker()
20129
21.3k
{
20130
21.3k
    ImGuiContext& g = *GImGui;
20131
21.3k
    g.DebugItemPickerBreakId = 0;
20132
21.3k
    if (!g.DebugItemPickerActive)
20133
21.3k
        return;
20134
20135
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20136
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
20137
0
    if (IsKeyPressed(ImGuiKey_Escape))
20138
0
        g.DebugItemPickerActive = false;
20139
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
20140
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
20141
0
    {
20142
0
        g.DebugItemPickerBreakId = hovered_id;
20143
0
        g.DebugItemPickerActive = false;
20144
0
    }
20145
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
20146
0
        if (change_mapping && IsMouseClicked(mouse_button))
20147
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
20148
0
    SetNextWindowBgAlpha(0.70f);
20149
0
    if (!BeginTooltip())
20150
0
        return;
20151
0
    Text("HoveredId: 0x%08X", hovered_id);
20152
0
    Text("Press ESC to abort picking.");
20153
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
20154
0
    if (change_mapping)
20155
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
20156
0
    else
20157
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
20158
0
    EndTooltip();
20159
0
}
20160
20161
// [DEBUG] Stack Tool: update queries. Called by NewFrame()
20162
void ImGui::UpdateDebugToolStackQueries()
20163
21.3k
{
20164
21.3k
    ImGuiContext& g = *GImGui;
20165
21.3k
    ImGuiStackTool* tool = &g.DebugStackTool;
20166
20167
    // Clear hook when stack tool is not visible
20168
21.3k
    g.DebugHookIdInfo = 0;
20169
21.3k
    if (g.FrameCount != tool->LastActiveFrame + 1)
20170
21.3k
        return;
20171
20172
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
20173
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
20174
2
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
20175
2
    if (tool->QueryId != query_id)
20176
0
    {
20177
0
        tool->QueryId = query_id;
20178
0
        tool->StackLevel = -1;
20179
0
        tool->Results.resize(0);
20180
0
    }
20181
2
    if (query_id == 0)
20182
2
        return;
20183
20184
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
20185
0
    int stack_level = tool->StackLevel;
20186
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20187
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
20188
0
            tool->StackLevel++;
20189
20190
    // Update hook
20191
0
    stack_level = tool->StackLevel;
20192
0
    if (stack_level == -1)
20193
0
        g.DebugHookIdInfo = query_id;
20194
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20195
0
    {
20196
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
20197
0
        tool->Results[stack_level].QueryFrameCount++;
20198
0
    }
20199
0
}
20200
20201
// [DEBUG] Stack tool: hooks called by GetID() family functions
20202
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
20203
0
{
20204
0
    ImGuiContext& g = *GImGui;
20205
0
    ImGuiWindow* window = g.CurrentWindow;
20206
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20207
20208
    // Step 0: stack query
20209
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
20210
0
    if (tool->StackLevel == -1)
20211
0
    {
20212
0
        tool->StackLevel++;
20213
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
20214
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
20215
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
20216
0
        return;
20217
0
    }
20218
20219
    // Step 1+: query for individual level
20220
0
    IM_ASSERT(tool->StackLevel >= 0);
20221
0
    if (tool->StackLevel != window->IDStack.Size)
20222
0
        return;
20223
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
20224
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
20225
20226
0
    switch (data_type)
20227
0
    {
20228
0
    case ImGuiDataType_S32:
20229
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
20230
0
        break;
20231
0
    case ImGuiDataType_String:
20232
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
20233
0
        break;
20234
0
    case ImGuiDataType_Pointer:
20235
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20236
0
        break;
20237
0
    case ImGuiDataType_ID:
20238
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20239
0
            return;
20240
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20241
0
        break;
20242
0
    default:
20243
0
        IM_ASSERT(0);
20244
0
    }
20245
0
    info->QuerySuccess = true;
20246
0
    info->DataType = data_type;
20247
0
}
20248
20249
static int StackToolFormatLevelInfo(ImGuiStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20250
0
{
20251
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20252
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20253
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20254
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20255
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20256
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20257
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20258
0
        return (*buf = 0);
20259
#ifdef IMGUI_ENABLE_TEST_ENGINE
20260
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20261
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20262
#endif
20263
0
    return ImFormatString(buf, buf_size, "???");
20264
0
}
20265
20266
// Stack Tool: Display UI
20267
void ImGui::ShowStackToolWindow(bool* p_open)
20268
0
{
20269
0
    ImGuiContext& g = *GImGui;
20270
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20271
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20272
0
    if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20273
0
    {
20274
0
        End();
20275
0
        return;
20276
0
    }
20277
20278
    // Display hovered/active status
20279
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20280
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20281
0
    const ImGuiID active_id = g.ActiveId;
20282
#ifdef IMGUI_ENABLE_TEST_ENGINE
20283
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20284
#else
20285
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20286
0
#endif
20287
0
    SameLine();
20288
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
20289
20290
    // CTRL+C to copy path
20291
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
20292
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
20293
0
    SameLine();
20294
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
20295
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
20296
0
    {
20297
0
        tool->CopyToClipboardLastTime = (float)g.Time;
20298
0
        char* p = g.TempBuffer.Data;
20299
0
        char* p_end = p + g.TempBuffer.Size;
20300
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
20301
0
        {
20302
0
            *p++ = '/';
20303
0
            char level_desc[256];
20304
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
20305
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
20306
0
            {
20307
0
                if (level_desc[n] == '/')
20308
0
                    *p++ = '\\';
20309
0
                *p++ = level_desc[n];
20310
0
            }
20311
0
        }
20312
0
        *p = '\0';
20313
0
        SetClipboardText(g.TempBuffer.Data);
20314
0
    }
20315
20316
    // Display decorated stack
20317
0
    tool->LastActiveFrame = g.FrameCount;
20318
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
20319
0
    {
20320
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
20321
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
20322
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
20323
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
20324
0
        TableHeadersRow();
20325
0
        for (int n = 0; n < tool->Results.Size; n++)
20326
0
        {
20327
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
20328
0
            TableNextColumn();
20329
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
20330
0
            TableNextColumn();
20331
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
20332
0
            TextUnformatted(g.TempBuffer.Data);
20333
0
            TableNextColumn();
20334
0
            Text("0x%08X", info->ID);
20335
0
            if (n == tool->Results.Size - 1)
20336
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
20337
0
        }
20338
0
        EndTable();
20339
0
    }
20340
0
    End();
20341
0
}
20342
20343
#else
20344
20345
void ImGui::ShowMetricsWindow(bool*) {}
20346
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
20347
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
20348
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
20349
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
20350
void ImGui::DebugNodeFont(ImFont*) {}
20351
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
20352
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
20353
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
20354
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
20355
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
20356
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
20357
20358
void ImGui::DebugLog(const char*, ...) {}
20359
void ImGui::DebugLogV(const char*, va_list) {}
20360
void ImGui::ShowDebugLogWindow(bool*) {}
20361
void ImGui::ShowStackToolWindow(bool*) {}
20362
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
20363
void ImGui::UpdateDebugToolItemPicker() {}
20364
void ImGui::UpdateDebugToolStackQueries() {}
20365
20366
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
20367
20368
//-----------------------------------------------------------------------------
20369
20370
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
20371
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
20372
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
20373
#include "imgui_user.inl"
20374
#endif
20375
20376
//-----------------------------------------------------------------------------
20377
20378
#endif // #ifndef IMGUI_DISABLE